[英]Difference between JSON.parse and .json() in Javasscript
我有一個簡單的angular2 http get調用,如下所示
import { Http, Response } from '@angular/http';
@Injectable()
export class ServiceBase {
protected resource: string;
constructor(private _http: Http) { }
getTnCByCountryCodeNdType(countryCode: string, tncType: string) {
let url = `${CONFIG.URL}/tnc?countryCode=${country}&tnc=${tnc}`;
return this._http.get(url, this.getHeader())
.map((res: Response) => {
return res.json();
});
}
}
收到時來自上面的錯誤響應,
我試過了
this.service
.getTnCByCountryCodeNdType('MY', this.tnc.toLowerCase())
.subscribe(x => {
//
},
(err: Response) => {
error = JSON.parse(err);
});
其中:err是響應錯誤;
它拋出了通常的json錯誤。
EXCEPTION:位於0的JSON中出現意外的令牌R.
出乎我的意料
error = err.json();
工作良好。 這兩者有什么區別,為什么第一個失敗? 任何幫助表示贊賞
JSON.parse需要一個JSON格式的字符串,但是你給它一個Response對象,它不是JSON,因此解析錯誤。
res.json()從Response對象中提取JSON格式的數據,並將數據轉換為JavaScript對象。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.