【问题标题】:Async pipe and ngFor is not displaying items异步管道和 ngFor 不显示项目
【发布时间】:2019-08-31 22:08:10
【问题描述】:

我希望*ngFor 能够迭代通过异步管道提供的http.get 的结果。项目没有被渲染,加载 div 也没有。

服务:

public getKeywords = () =>  {
   return this.http.get<getKeywords>(`${this.uri}/keywords`);
}

界面:

interface getKeywords {
  keywords: Array<object>;
}

TS:

export class KeywordsSettingsComponent implements OnInit {

  public currentKeywords$: any;

  constructor(private profileProvider: ProfileProvider) { }

  ngOnInit() {
    this.currentKeywords$ =
      this.profileProvider.getKeywords().pipe(map(({ keywords }) => keywords));
  }
}

模板:

<div class="row">
  <ng-template *ngIf="currentKeywords$ | async as currentKeywords ; else loading">
    <div class="keyword" * ngFor="let keywordObj of currentKeywords">
      {{ keywordObj.keyword }}
      <span class="icon-close"> </span>
    </div>
  </ng-template>
  <ng-template #loading> Loading keywords...</ng-template>
</div>

加载 div 没有显示的事实表明没有发出值。如果我像这样订阅 ngOnInt:

 this.currentKeywords$ = this.profileProvider.getKeywords().pipe(map(({keywords}) => keywords), share()).subscribe(res => res));

加载 div 确实显示,但结果未呈现在 *ngFor div 中。但是我知道异步管道管理订阅/取消订阅,因此在 ngOnInit 中订阅应该是不必要的。


来自 http.get 的结果: HTTP 调用返回一个具有多个属性的对象,其中一个是“关键字”,其中包含一个对象数组。我正在使用 map() 来映射到单个属性并访问对象数组。

{..."keywords":[{"id":331,"keyword":"spam"},{"id":330,"keyword":"foo"},{"id":332,"keyword":"brexit"}]}

【问题讨论】:

  • 我也会检查开发工具,看看你的 HTTP 调用返回了什么。你可能期待一个数组,而返回可能只是一个对象。
  • HTTP 调用返回一个对象,该对象的属性“keywords”是一个对象数组。

标签: angular rxjs


【解决方案1】:

基于 HTTP 正在返回一个对象的事实,您需要更改此内容:

<div class="keyword" * ngFor="let keywordObj of currentKeywords">

到这里:

<div class="keyword" *ngFor="let keywordObj of currentKeywords.keywords">

我也会改变这个:

this.currentKeywords$ =
      this.profileProvider.getKeywords().pipe(map(({ keywords }) => keywords));

对此也是如此:

this.currentKeywords$ = this.profileProvider.getKeywords();

...因为该地图并没有真正映射任何东西。

您可能还需要将您的第一个 &lt;ng-template 更改为例如 &lt;div ,因为我想它不会自行渲染。

希望对你有帮助。

【讨论】:

  • HTTP 调用返回一个具有多个属性的对象,其中一个是包含对象数组的“关键字”。我正在使用 map() 来映射到单个属性并访问对象数组。
猜你喜欢
  • 2018-04-18
  • 2020-01-15
  • 1970-01-01
  • 1970-01-01
  • 2019-04-11
  • 2016-02-18
  • 2018-02-03
  • 1970-01-01
  • 2016-07-25
相关资源
最近更新 更多