我有一个简单的angular2 http get call ,如下所示
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错误。
出乎我的意料
error = err.json();
工作正常。两者之间有什么区别,为什么第一个失败?任何帮助表示赞赏
最佳答案
JSON.parse
是JavaScript object 。它将包含JSON的字符串解析为该字符串表示的内容。您不会将其传递给对象。显然,您的err
不是字符串。
Angular 2的res
提供给您的err
和http
是 Response
对象,它们说是从Body
派生的。我在Angular 2文档中看不到任何内容来说明Body
是什么,但显然它具有json
函数,该函数返回将响应数据解析为JSON的结果。那不是JavaScript,而是Angular的东西。 (如以上链接所述,它的灵感来自 fetch
,但与ojit_a不同)。
关于javascript - JavaScript中JSON.parse和.json()之间的区别,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/43654224/