I\'m learning Angular2 and Typescript. I\'m working through the Heroes tutorial on angular.io, but applying it to a project I\'m converting from ASP.Net. I\'ve run into a pr
I think that your problem is located here:
getRisks(): Observable<RiskListSummary[]> {
return this.http.get(this.serviceUrl)
.map(this.extractData()) <== passing result of function
.catch(this.handleError()); <== passing result of function
}
You could use just passing function
reference:
getRisks(): Observable<RiskListSummary[]> {
return this.http.get(this.serviceUrl)
.map(this.extractData)
.catch(this.handleError);
}
but this way you will lose this
.
Or you could use bind method to retain this
:
getRisks(): Observable<RiskListSummary[]> {
return this.http.get(this.serviceUrl)
.map(this.extractData.bind(this))
.catch(this.handleError.bind(this));
}
however you will lose type checking.
I would leverage arrow functions to be able to use lexical this:
getRisks(): Observable<RiskListSummary[]> {
return this.http.get(this.serviceUrl)
.map(res => this.extractData(res))
.catch(err => this.handleError(err));
}
Without it, the this
variable will point to the function where the call is made, instead of the instance that contains getRisks()
.
Typescript is a compiler tool, which will always give type check compile error as here in this case getRisk method should specify that it is returning Observable of type RiskListSummary, so that the tool should recognize what is expected out of this method and will check the type safety when used in subscribe method.
I had same problem, however no matter how I changed as above mentioned,It still not working. Until my college found this map, catch defination as VSC prompted
so the proper change should be like (add type cast the following place)
getRisks(): Observable<RiskListSummary[]> {
return this.http.get(this.serviceUrl)
.map<RiskListSummary[]>(this.extractData)
.catch<RiskListSummary[]>(this.handleError);
}
I am new to TypeScript. so this kind of [method signature] really give me a hammer on the head :(
But finally it worked out :)
According to the getRisks()
fn, you are types to return Observable<RiskListSummary[]>
. However in your code, you are returning body.data || {}
. I believe you need to interface your RiskListSummary[] to your body.data.
I found the next: AccessTokens was missing. So,i made the change and it workted: On your model (in my case Country) edit de file and change from:
export interface CountryInterface {
"id"?: any;
"name": string;
"order"?: number;
}
export class Country implements CountryInterface {
"id": any;
"name": string;
"order": number;
....
}
To:
export interface CountryInterface {
"id"?: any;
"name": string;
"order"?: number;
accessTokens: any[];
}
export class Country implements CountryInterface {
"id": any;
"name": string;
"order": number;
accessTokens: any[];
...
}