Angular2:res.json不是函数 [英] Angular2: res.json is not a function
本文介绍了Angular2:res.json不是函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试在我的代码中使用以下服务:
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() );
}
}
问题是,在运行时它抱怨:
res.json is not a function
我已将res的数据类型定义为Response,但仍然抱怨
.map( (res: Response) => res.json() )
如果我将地图替换为"subscribe",则效果很好:
.subscribe( res =>{
res.json();
console.log("City is:"+ res.json().city.name)
});
解决方案
对于它的价值,在Angular 5中,我发现如果响应是纯json,只需返回res
即可解决res.json is not a function
错误./p>
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)
});
解决方案
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.
这篇关于Angular2:res.json不是函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文