Actually getting the user information and saving into a variable - kik

So, I have the following code on my site:
if ( kik.hasPermission() ) {
// do something
} else {
kik.getUser(function (user) {
if ( !user ) {
// error
} else {
typeof user.username; // 'string'
typeof user.fullName; // 'string'
typeof user.firstName; // 'string'
typeof user.lastName; // 'string'
typeof user.pic; // 'string'
typeof user.thumbnail; // 'string'
// set them ^ to vars here
}
});
}
But I would like to set the data (user.username, etc.) into variables. I can't seem to work it out. All help is appreciated.

The user paramter is an object containing the data you need.
You can access and store the data like this
var username = user.username;
var fullName = user.fullName;
...
Be aware that user.pic and user.thumbnail are links to the images. If you want to store the image data you have to fetch it from the link first.

Related

I am trying to take data from "blog" and push it to "blogs", yet an error occurs

I'm getting the following error:
**Error1:** Cannot find a differ supporting object '[object Object]' of type 'object'. NgFor only supports binding to Iterables, such as Arrays. Did you mean to use the keyvalue pipe?
**Error2:** this.blogs.push is not a function
My code looks like this:
export class BlogComponent {
blogs: Array<blogType>;
constructor() {
this.blogs = new Array<blogType>();
}
ngOnInit() {
this.blogs = JSON.parse(localStorage.getItem("blogs")!);
}
addBlog(title: any, content: any) {
let blog = new blogType(title.value, content.value);
if (localStorage.getItem('blogs')) {
this.blogs = JSON.parse(localStorage.getItem('blogs')!);
}
this.blogs.push(blog); //error occurs because of that line. Runtime error
localStorage.setItem('blogs', JSON.stringify(this.blogs));
title.value = '';
content.value = '';
alert('Blog Added!');
}
I am trying to take data from the "blog" array and push it to the "blogs" array in order to store it in the localstorage. Yet I get an error because of the folowing line: this.blogs.push(blog);
Check the contents of LocalStorage for null before you parse it and assign to this.blogs:
ngOnInit() {
var current = localStorage.getItem('blogs');
if (current !== null) {
this.blogs = JSON.parse(current);
}
console.log('this.blogs is: ' + this.blogs);
}

Error argument of type 'Item' is not assignable to parameter of type 'string'. TS2345

I am getting error with type 'string'. TS2345
Argument of type 'Item' is not assignable to parameter of type
'string'. TS2345
filter(resortList:ResortResult[], selectedFilters:SelectedFilters) {
return resortList
.filter(resort => {
let roomTypes = resort.available.flat().map(room => room.roomType);
let activities = resort.activities;
let hasRoomType = selectedFilters["room"].some(
(rt:Item)=> roomTypes.indexOf(rt) > -1
);
let hasActivity = selectedFilters["activity"].some(
(act:Item) => ((activities.indexOf(act.value)) > -1)
);
return !(
(selectedFilters["area"].length === 0 ||
selectedFilters["area"].indexOf(resort.city) > -1) &&
// (selectedFilters["views"].length === 0 ||
// selectedFilters["views"].indexOf(resort.city) > -1) &&
(selectedFilters["activity"].length === 0 || hasActivity) &&
(selectedFilters["room"].length === 0 || hasRoomType)
);
})
.map(resort => {
return resort.propertyCode;
});
}
How can I fix this error with react-typescript? Thanks alot!
So it looks like you are using typescript. Typescript is a strongly-typed language, meaning that typically you have to define the datatype for a variable before you can use it. This also means that you can only set a variable to the type that it is assigned.
What this error is saying is that you are trying to assign a value that is not a string to a variable where the type is "string". More specifically, it looks like you are trying to assign a whole object (of type "Item") to a variable with the type "string".
You need to check your code and make sure that you are not trying to assign the wrong datatype somewhere. In the small code snippet that you gave, it's a bit difficult to see where the error is.
When you have to assign a type to an array callback, like (rt:Item) => and (act:Item) =>, that's a sign that some type is either missing or incorrect higher up in the chain. The callback will get the correct type automatically if the array itself has the correct type.
It seems like the error is most likely in your indexOf calls, though it's hard to know for sure without seeing your types for ResortResult and SelectedFilters. You are checking that roomTypes contains an element rt which is an Item. If roomTypes is an array of string then you would need to check roomTypes.indexOf(rt.value) instead of roomTypes.indexOf(rt).
If it is in fact an array of Item, you might have confusing results because indexOf is checking for strict equality. That is, it's checking that you have literally the same object instance in both places.
This code passes all type checks, but it might not match your actual types:
interface Item {
value: string;
}
interface ResortResult {
available: {roomType: string}[][];
activities: string[];
propertyCode: string;
city: string;
}
interface SelectedFilters {
room: Item[];
activity: Item[];
area: string[];
}
function filter(resortList: ResortResult[], selectedFilters: SelectedFilters) {
return resortList
.filter(resort => {
let roomTypes = resort.available.flat().map(room => room.roomType);
let activities = resort.activities;
let hasRoomType = selectedFilters["room"].some(
(rt) => roomTypes.indexOf(rt.value) > -1
);
let hasActivity = selectedFilters["activity"].some(
(act) => ((activities.indexOf(act.value)) > -1)
);
return !(
(selectedFilters["area"].length === 0 ||
selectedFilters["area"].indexOf(resort.city) > -1) &&
// (selectedFilters["views"].length === 0 ||
// selectedFilters["views"].indexOf(resort.city) > -1) &&
(selectedFilters["activity"].length === 0 || hasActivity) &&
(selectedFilters["room"].length === 0 || hasRoomType)
);
})
.map(resort => {
return resort.propertyCode;
});
}
TypeScript Playground Link
You have to assign a different value to a variable as you cannot assign a string to all of the variables.

Dynamic state update in mobx react typescript

I want to have a function that accepts only the state declared in mobx. I currently have this code.
class DialogStore {
status: boolean = false;
title: string = '';
content: string = '';
btnText: string = '';
icon: JSX.Element | string = '';
type: 'success' | 'error' = 'success';
constructor() {
makeAutoObservable(this);
}
toggle(status: boolean) {
this.status = status
}
success(content: string) {
this.type = 'success';
this.status = true;
this.content = content;
}
error(content: string) {
this.type = 'error';
this.status = true;
this.content = content;
}
}
I want to add a dynamic function like this:
update(payload: TypeOfState) {
Object.keys(payload).forEach(property => {
this[property] = payload[property];
})
}
I tried to place any as my payload type but it gives me this error Element implicitly has an 'any' type because expression of type 'string' can't be used to index type 'DialogStore'. I want the payload to only accept the state I declared at the top.
If I understand you correctly you want to have single function instead of toggle, success and error?
Would something like this work for your case?
class DialogStore {
// ...
update(payload: StateToUpdate) {
Object.keys(payload).forEach((property) => {
this[property] = payload[property];
});
}
}
type StateToUpdate = Partial<Pick<DialogStore, 'status' | 'type' | 'content'>>
To avoid TS error you could disable flag "suppressImplicitAnyIndexErrors": true altogether in your tsconfig.json or use some typecasting:
Object.keys(payload).forEach((property) => {
(this as any)[property] = payload[property as keyof StateToUpdate];
});
I think there is no easy way to mitigate this type of error in TS right now, I might be wrong though.

Type 'Observable<any>' is not assignable to type 'StoresSummaryResults'. Property 'Data' is missing in type 'Observable<any>'

I am new to using the Observable with Angular 2 and my structure will not receive the results, even though I can validate the response from my REST API.
I have the following data class in Typescript.
import { RESTResult } from '../common/RESTResult'; // Common Response Structure
import { StoresSummaryData } from './StoresSummaryData'; // Structure of records being returned as an array
export class StoresSummaryResults extends RESTResult {
Data: Array<StoresSummaryData>; // Data[] is array ofStoresSummaryData structure ({ field1, field2 ...)
constructor() {
super();
this.Data = new Array<StoresSummaryData>(); // Ensure 1 records exists for testing
this.Data.push(new StoresSummaryData(0, 0));
}
}
The results are retrieved from the REST API
getResults(): Observable<StoresSummaryResults> { // Structure
return this.http.get(this.RequestHttpPath)
.map(this.extractData)
.catch(this.handleError);
};
private extractData(res: Response) {
let body = res.json();
return body.data || {};
}
StoreInfo: StoresSummaryResults;
public constructor(private storesService: StoresService) { }
showResults(): void {
this.StoreInfo = this.storesService.getResults();
}
I get the error:
Typescript Error
Type 'Observable<StoresSummaryResults>' is not assignable to type 'StoresSummaryResults'. Property 'Data' is missing in type 'Observable<StoresSummaryResults>'.
I do have the Data structure though defined, so I am not sure what to correct.
The StoreInfo property is typed as a StoresSummaryResults, but you are trying to assign it the return value of storesService.getResults() which is Observable<StoresSummaryResults>.
So either change StoreInfo to be typed as Observable<StoresSummaryResults>, or assign it in a subscription:
this.storeSevice.getResults()
.subscribe(results => this.StoreInfo = results);

How to retrieve query parameter in Server Script

I'm using Windows Azure Mobile Service to build the backend for my app. For server script's read operation, now I want to retrieve the query parameter like $filter, $select in the script, etc. Any idea?
After hacking around with the 'query' object in the 'read' function's parameter (by using console.log ), I finally found the solution:
function isObject(variable) {
return variable !== null &&
variable !== undefined &&
typeof variable === 'object';
}
// Find all the member-value pairs from the expression object
function findMemberValuePairsFromExpression (expr, ret) {
if (!isObject(expr)) {
return null;
}
ret = ret || {};
for (var name in expr) {
if (expr.hasOwnProperty(name)) {
var prop = expr[name];
if (name === 'parent') { // Ignore parent property since it's added by us
continue;
}
else if (name === 'left') { // member expression are in the left subtree
if (isObject(prop)) {
prop.parent = expr; // Remember the parent
findMemberValuePairsFromExpression(prop, ret);
}
}
else if (name === 'member') {
// Found a member expression, find the value expression
// by the knowledge of the structure of the expression
var value = expr.parent.right.value;
ret[prop] = value;
}
}
}
if (expr.parent) {
// Remove the added parent property
delete expr.parent;
}
return ret;
}
// Get the filters component from query object and
// find the member-value pairs in it
function findMemberValuePairsFromQuery (query) {
var filters = query.getComponents().filters;
return findMemberValuePairsFromExpression(filters);
}
function read (query, user, request) {
request.execute();
}
Remember that this approach heavily relies on the inner structure of the query object so it may break in the future.
query.getComponents() also returns other parts of the query, like 'select', 'skip', 'top', etc. Basically anything of the oData protocol

Resources