ngFor中的角度异步管道返回null

时间:2019-06-05 07:51:39

标签: angular asynchronous rxjs angularfire ngfor

我有以下代码:

<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吗?

1 个答案:

答案 0 :(得分:0)

由于某些原因,它起作用:

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运算符来避免开头出现空错误)。

相关问题