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)
});
就其价值而言,在 Angular 5 中,我发现res.json is not a function
错误,如果响应是纯 json,只需返回res
即可修复。
Try to import 'rxjs/add/operator/map';
instead of import 'rxjs/Rx';
. That should fix the problem.
You Don't need to use this: .map((res: Response) => res.json() );
or .map(res => res.json());
because HttpClient.get()
feeds or applies to res.json()
automatically and returns Observable<HttpResponse<string>>
.
You no longer need to call this function yourself again. Just simply put it this way: .map(res => res );
this resolves or solve the problem.
You do not need to call res.json()
if you response is already a Json you can directly work with res
you do not even need to use map
in this case
getData(){
return this.http.get("URI");
}
Try to put only like this
.map((response: Response) => response)
This work surely in Angular
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.