【问题标题】:Angular2 http get first elementAngular2 http获取第一个元素
【发布时间】:2017-08-10 10:44:23
【问题描述】:

我想从这个 JSON 文件中获取“id”元素的值:

{
"data": {
    "id": 2,
    "first_name": "lucille",
    "last_name": "bluth",
    "avatar": "https://s3.amazonaws.com/uifaces/faces/twitter/josephstein/128.jpg"
}

}

这是我获取数据的代码:

getData() {

    return this.http.get('https://reqres.in/api/users/2')
    .map((respone: Response) => respone.json());
}

我怎样才能只获得“id”值?

【问题讨论】:

  • 你要返回一个 observable 吗?

标签: angular http get observable subscribe


【解决方案1】:

您也可以在显示数据的组件的 HTML 中执行此操作。 例如:

<div *ngFor = 'let first of http'>
    {{first.id}}
</div>

【讨论】:

    【解决方案2】:

    假设你使用的是RxJs,调用getData()后,你必须订阅结果,然后解析数据。

    this.getData().subscribe(result => {
    
        // handle the response
    
        return result.data.id;
    
    });
    

    【讨论】:

      【解决方案3】:

      你也可以这样做:

      getData() {
          return this.http.get('https://reqres.in/api/users/2')
                          .map((respone: Response) => respone.json().data.id);
      }
      

      将仅返回响应中的 id 字段,而不是整个数据对象。

      【讨论】:

        【解决方案4】:

        假设您从服务中返回一个 Observable, 您可以使用各种 RxJs first operator

        this.serviceName.getData().first(x => console.log(x.id)) //logs the first id
                                  .subscribe(data => console.log(data); // logs the stream of data
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2022-08-17
          • 2017-02-19
          • 1970-01-01
          • 2011-01-11
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2021-10-27
          相关资源
          最近更新 更多