【发布时间】:2016-08-26 08:43:52
【问题描述】:
我正在尝试在我的代码中使用以下服务:
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( res =>{
res.json();
console.log("City is:"+ res.json().city.name)
});
【问题讨论】:
-
您确定您的请求返回的是 json 吗?
-
当我有 functionA() 调用 functionB() 并且都使用了对 map() 的调用时,我遇到了这个问题。到调用 functionA map() 时,B 的 map 已经将 res.json() 转换为对象数组,这意味着 A 没有可用的 json。修复是从 functionB() 中删除 map() 调用,因此只调用了顶层 map()
标签: angular