[英]Angular2: res.json is not a function
我正在嘗試在我的代碼中使用以下服務:
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 的數據類型定義為響應,但仍然抱怨
.map( (res: Response) => res.json() )
如果我用訂閱替換地圖它工作正常:
.subscribe( res =>{
res.json();
console.log("City is:"+ res.json().city.name)
});
就其價值而言,在 Angular 5 中,我發現res.json is not a function
錯誤,如果響應是純 json,只需返回res
即可修復。
嘗試import 'rxjs/add/operator/map';
而不是import 'rxjs/Rx';
. 那應該可以解決問題。
你不需要使用這個: .map((res: Response) => res.json() );
或.map(res => res.json());
因為HttpClient.get()
提供或應用於res.json()
並返回Observable<HttpResponse<string>>
。
您不再需要自己再次調用此函數。 簡單地說就是這樣: .map(res => res );
這可以解決或解決問題。
如果您的響應已經是 Json,則無需調用res.json()
您可以直接使用res
在這種情況下甚至不需要使用map
getData(){
return this.http.get("URI");
}
嘗試只放這樣
.map((response: Response) => response)
這項工作肯定適用於 Angular
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.