Search code examples
angular-cliangular-httpclient

Migrating from @angular/http to @angular/common/http


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)

Solution

  • 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)