【问题标题】:How to display data from Observable in Angular component如何在 Angular 组件中显示来自 Observable 的数据
【发布时间】:2020-10-16 09:06:06
【问题描述】:

我在组件中显示 Observable 对象时遇到问题。

我的 Json 结构是:

{ 
  "data": [
    {
     "id": "123",
     "name": "test",
    } 
  ], 
  "pagination": null
}

所以我创建了将这个 json 映射到 .ts 的接口

export interface Paginated<T>{
   data: Array<T>;
   pagination: Pagination;
}

在我的组件中,我有这个 json 的 Observable 对象:

 this.httpClient.get<Paginated<Event>>(`${environment.apiUrl}/events`);

而且我不知道如何使用异步管道显示 Observable 内部的属性 data,因为这个 json 不是数组 - 它是具有两个属性的对象 - datapagination 所以我不能简单地将 *ngFor 与异步管道一起使用,因为这个对象不是数组。

所以我的问题是当我收到 Observable 时如何在组件中显示这个属性数据我不能使用 *ngFor... 如何从这个 Observable 解压数据属性

【问题讨论】:

    标签: javascript angular api get observable


    【解决方案1】:

    试试这个

    response$: Observable<Paginated<Event>>;
    constructor() {
      response$ = this.httpClient.get<Paginated<Event>>(`${environment.apiUrl}/events`);
    }
    

    在你的组件中

    <li *ngFor="let dataEl of (response$ | async)?.data">{{dataEl.name}}</li>
    

    【讨论】:

      【解决方案2】:

      如果您想从 observable 中提取值,可以通过以下方式订阅其值:

      data: Array<T> = [];
      
      constructor(){
         this.httpClient.get<Paginated<Event>>(`${environment.apiUrl}/events`).subscribe((response) => {
      
            // then extract the data from response over here
            const {data, pagination} = response;
      
            // assign the extracted 'data' array to a component variable named data.
            this.data = data;
      
         });
      }
      

      然后可以在html模板中使用

      <li *ngFor="let el of (data)">{{data.name}}</li>
      

      【讨论】:

        猜你喜欢
        • 2017-02-21
        • 1970-01-01
        • 2021-12-07
        • 1970-01-01
        • 2018-06-29
        • 2021-02-26
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多