Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular2: res.json is not a function

Tags:

angular

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, in run time it complains with:

res.json is not a function

I have defined the datatype of res as Response, but still complains

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

if i replace the map with subscribe it works fine:

.subscribe( res =>{
                res.json();
                console.log("City is:"+ res.json().city.name)
            });
like image 684
Sal-laS Avatar asked Aug 26 '16 08:08

Sal-laS


2 Answers

For what its worth, in Angular 5 I found that the res.json is not a function error can be fixed by just returning res if the response is pure json.

like image 145
jcaruso Avatar answered Oct 06 '22 08:10

jcaruso


Try to import 'rxjs/add/operator/map'; instead of import 'rxjs/Rx';. That should fix the problem.

like image 43
Stefan Svrkota Avatar answered Oct 06 '22 07:10

Stefan Svrkota