I am migrating an angular-cli application from "@angular/http" to "@angular/common/http" but are having a some problems getting it to work.
I have a function that makes a request against my API and get the following json back.
{"Categories":[
{"name":"my first category","routetype":"category"},
{"name":"my second category","routetype":"category"}
]}
I am mapping that to class
export class Category {
name: string;
routetype: string;
}
Current code (working):
import { Http, Response } from '@angular/http';
...
getCategories(context: SiteContext): Observable<Array<Category>> {
return this.http.get(routes.getCategories(context), { cache: true })
.map((res: Response) => <Array<Category>>res.json().Categories)
.do(data => console.log(data))
.catch(this.handleError);
}
New code (Not working).
import { HttpClient } from '@angular/common/http';
...
getCategories(context: SiteContext): Observable<Array<Category>> {
return this.httpClient.cache().get(routes.getCategories(context))
.map((res: Response) => <Array<Category>>res.json().Categories)
.do(data => console.log(data))
.catch(this.handleError);
}
In vs.code I get this error message:
[ts] Property 'Categories' does not exist on type 'Promise<any>'
on this line:
.map((res: Response) => <Array<Category>>res.json().Categories)
Angular 4.3+ HttpClient has a completely different API. It already does the json parsing for you.
So your code should look more like:
this.httpClient.get<Categories>().map(data => data.Categories).do(data => console.log(data).catch(this.handlError);
(Your Response type belongs to the old API)
What was a great help for me while doing the equivalent migration, was generating a small jhipster test project and analyzing how the jhipster entities are generated using the new HttpClient. Not exacly an answer but might help.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With