我在理解如何正确使用 Angular 2 中的 observables 时遇到了一些困难。我使用以下查询:
let headers = new Headers({ 'Content-Type': 'application/json' });
let options = new RequestOptions({ headers: headers });
return this.http.get('http://localhost:3000/admin/is-admin.json', options)
.map(res => res)
.catch(this.handleError); }
API 调用返回一个 bool 值 true 或 undefined,但我无法从我的函数中返回该值。目前它返回一个对象,我希望它直接返回 bool 值。当我将 map 线更改为:
.map(res => JSON.parse(res))
如果我将其更改为:
,我会收到 JSON 解析错误 .map(res => res.data)
我收到一条错误,表明响应对象上不存在数据。有人知道我应该做什么吗?答案可能非常基本,但我已经寻找它很长一段时间了......
最佳答案
我将通过获取响应负载的文本值来使用以下内容:
let headers = new Headers({ 'Content-Type': 'application/json' });
let options = new RequestOptions({ headers: headers });
return this.http.get('http://localhost:3000/admin/is-admin.json', options)
.map(res => { // <-----
let responsePayload = res.text();
return (responsePayload != null) ? Boolean(res.text()) : responsePayload;
}))
.catch(this.handleError);
您还可以尝试调用 json
方法:
let headers = new Headers({ 'Content-Type': 'application/json' });
let options = new RequestOptions({ headers: headers });
return this.http.get('http://localhost:3000/admin/is-admin.json', options)
.map(res => res.json()) // <-----
.catch(this.handleError);
关于javascript - 从 Angular 2 中的 observable 中提取数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37069712/