我有一个简单的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);
});
其中:错误是响应错误;
它抛出了常见的json错误。
EXCEPTION:位于0的JSON中的意外标记R
令我惊讶
error = err.json();
工作正常。这两者有什么区别,为什么第一个失败?任何帮助表示赞赏
答案 0 :(得分:3)
JSON.parse
是一个JavaScript的东西。它将包含JSON的字符串解析为该字符串所代表的任何内容。你不传递它的对象。显然,您的err
不是字符串。
Angular 2 res
为您提供的err
和http
是Response
个对象,表示它来自Body
。我在Angular 2文档中看不到Body
是什么,但显然它有一个json
函数,它返回将响应数据解析为JSON的结果。这不是一个JavaScript的东西,这是来自Angular的东西。 (如上面的链接所示,它的灵感来自 - 但不一样 - fetch
。)
答案 1 :(得分:2)
JSON.parse需要一个JSON格式的字符串,但是你给它一个Response对象,它不是JSON,因此解析错误。
res.json()从Response对象中提取JSON格式的数据,并将数据转换为JavaScript对象。