首页 > 解决方案 > ngFor 内的 Angular 异步管道返回 null

问题描述

我有以下代码:

<ng-container *ngFor="let category of categories | async">
  {{ events | async | json }}
</ng-container>



this.categories = this.db
  .collection('categories')
  .valueChanges();

this.events = this.categories
  .pipe(switchMap((categories: { category: EventCategory }[]) => categories))
  .pipe(mergeMap((category: { category: EventCategory }) => {
    return this.db
      .collection('events')
      .doc(category.category)
      .collection('items', ref => ref
        .where('endTime', '>=', +new Date()))
      .valueChanges()
      .pipe(map((events: Event[]) => events.map(mapToDate)))
      .pipe(map((events: Event[]) => ({ [category.category]: events })));
  }))
  .pipe(scan((acc: any, curr: { events: Event[] }) => ({ ...acc, ...curr }), {}))
  .pipe(debounceTime(100));

结果null适用于每个类别的事件。最终目标是:

<ng-container *ngFor="let category of categories | async">
  {{ (events | async)[category.category] | json }}
</ng-container>

这可以按预期工作:

  {{ events | async | json }}

知道为什么订阅事件在类别订阅中返回 null 吗?

标签: angularasynchronousrxjsangularfirengfor

解决方案


出于某种原因,这有效:

this.events = this.db
  .collection('categories')
  .valueChanges()
  .pipe(switchMap((categories: { category: EventCategory }[]) => categories))
  .pipe(mergeMap((category: { category: EventCategory }) => {
    return this.db
      .collection('events')
      .doc(category.category)
      .collection('items', ref => ref
        .where('endTime', '>=', +new Date()))
      .valueChanges()
      .pipe(map((events: Event[]) => events.map(mapToDate)))
      .pipe(map((events: Event[]) => ({ [category.category]: events })));
  }))
  .pipe(scan((acc: any, curr: { events: Event[] }) => ({ ...acc, ...curr }), {}))
  .pipe(debounceTime(100))
  .pipe(startWith({}));

(不同之处在于我不使用可观察类别作为初始源,而是再次查询类别集合,添加了 startWith 运算符,因为我不能使用 elvis 运算符来避免一开始出现 null 错误)。


推荐阅读