3

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)
Tony
  • 1,394
  • 5
  • 22
  • 48

2 Answers2

5

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)

Cyprien Autexier
  • 1,948
  • 16
  • 20
1

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.

Hubert Schumacher
  • 1,683
  • 1
  • 16
  • 25