Angular2: res.json is not a function 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 不是一个函数
我已经定义了 res 的数据类型为 Response,但仍然报错
.map( (res: Response) => res.json() )
如果我用 subscribe 替换 map,它就能正常工作:
.subscribe( res =>{ res.json(); console.log("City is:"+ res.json().city.name) });
在Angular 5中,如果返回的响应是纯json,可以通过返回res来解决"res.json is not a function"错误。
解决方法:
import { map } from 'rxjs/operators'; ... this.http.get(url) .pipe( map(res => { if (res.status === 200) { return res; } else { throw new Error('Response status is not 200'); } }), map(res => res.json()) ) .subscribe(data => { console.log(data); }, error => { console.error(error); });
或者可以使用toPromise()方法将Observable转换为Promise对象。
解决方法:
import 'rxjs/add/operator/toPromise'; ... this.http.get(url) .toPromise() .then(res => res.json()) .then(data => { console.log(data); }) .catch(error => { console.error(error); });
这些解决方法可以帮助你解决"res.json is not a function"错误。