Angular2: res.json is not a function

I am trying to use the following service in my code:

import {Injectable} from '@angular/core'; import {Http,Response} from "@angular/http"; import 'rxjs/Rx'; @Injectable() export class HttpService{ constructor(private http : Http){} getData(){ return this.http.get("URI") .map( (res: Response) => res.json() ); } } 

The problem is that at runtime it complains:

 res.json is not a function 

I defined the res data type as Response, but still complaining

 .map( (res: Response) => res.json() ) 

if I replace the card with a subscription, it works fine:

 .subscribe( res =>{ res.json(); console.log("City is:"+ res.json().city.name) }); 
+3
source share
3 answers

For what it's worth, in Angular 5, I found that the res.json is not a function error can be res.json is not a function simply returning res if the answer is pure json.

+10
source

Try import 'rxjs/add/operator/map'; instead of import 'rxjs/Rx'; . This should solve the problem.

+5
source

Try to deliver only as

 .map((response: Response) => response) 

This work is done in Angular

-1
source

Source: https://habr.com/ru/post/1265892/


All Articles