显示来自 httpClient 迭代 ngFor 的 Angular4 响应数据

Display Angular4 Response Data From httpClient Iteration ngFor

我有来自 Angular 4

的代码

我在控制台中有这个(数组对象)响应

而且我想用*ngFor中的这个数据来迭代这个对象,我怎样才能得到这个?谢谢

因为你用{observe: 'reaponse'}代替HttpClient.get,会有完整的回复(header和body),你可以用*ngFor来迭代器 data.body 通过将其公开为 public 变量,如下所示:

data: any;

this.http.get(..., {observe: 'response'})
    .subscribe(data => this.data = data.body);

模板代码示例:

<div *ngFor="let item of data">
  {{item.address}}
</div>

如果没有 {observe: 'response'}

HttpClient.get 将默认 return body 响应。您也可以在没有 {observe: 'response'} 的情况下实现它,如下所示:

data: any;

this.http.get(...)   // without observe: response
    .subscribe(data => this.data = data);

模板代码示例:

<div *ngFor="let item of data">
  {{item.address}}
</div>

您还可以使用 async 管道订阅和取消订阅 template,而无需使用 public 变量公开数据:

data$: any;

this.data$ = this.http.get(...)
// or 
this.data$ = this.http.get(..., {observe: 'reaponse'}).map(data => data.body);

模板代码示例:

<div *ngFor="let item of data$ | async">
  {{item.address}}
</div>