[英]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, in run time it complains with:问题是,在运行时它抱怨:
res.json is not a function
I have defined the datatype of res as Response, but still complains我已经将 res 的数据类型定义为响应,但仍然抱怨
.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';
尝试import 'rxjs/add/operator/map';
instead of import 'rxjs/Rx';
而不是import 'rxjs/Rx';
. . That should fix the problem.那应该可以解决问题。
You Don't need to use this: .map((res: Response) => res.json() );
你不需要使用这个: .map((res: Response) => res.json() );
or .map(res => res.json());
或.map(res => res.json());
because HttpClient.get()
feeds or applies to res.json()
automatically and returns Observable<HttpResponse<string>>
.因为HttpClient.get()
提供或应用于res.json()
并返回Observable<HttpResponse<string>>
。
You no longer need to call this function yourself again.您不再需要自己再次调用此函数。 Just simply put it this way: .map(res => res );
简单地说就是这样: .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如果您的响应已经是 Json,则无需调用res.json()
您可以直接使用res
在这种情况下甚至不需要使用map
getData(){
return this.http.get("URI");
}
Try to put only like this尝试只放这样
.map((response: Response) => response)
This work surely in Angular这项工作肯定适用于 Angular
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.