javascript - 从 Angular 2 中的 observable 中提取数据

标签 javascript angular

我在理解如何正确使用 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/

相关文章:

javascript - “this”在 JavaScript 类方法中未定义

javascript - 如何在 Django 中应用 csrf_token

javascript - 类型错误 : button is null but working fine in console

angular - 如何更改 ag Grid 中的排序图标,如 angular Font Awesome 图标中的 Angular 箭头图标?

Angular 2 Quickstart - 我的应用程序组件未加载

javascript - 在 ReactJs 中创建动态 svg 图标组件

javascript - 使用 TinyMCE execCommand 插入元素并保留引用

angular - 处理http.get()中的错误

angular - NativeScript-Angular - KeyboardEvent 未定义

Angular 2共享服务变量返回未定义