angular - 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 吗?
解决方案
出于某种原因,这有效:
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 错误)。
推荐阅读
- acumatica - 如何使用 acumatica screenID 添加新的顶级实体(以休息 Web 服务端点)?
- typescript - 在 APIGatewayProxyEvent 中,哪个字段会给我 URL?
- javascript - 如果我知道字符串的值,我可以将其直接插入剪贴板而不执行 execCommand('copy')
- android - TensorFlow Lite 2.0 高级 GPU 在 Android 上使用 C++
- c# - 身份在 .NET Core 项目中不起作用
- python - 我怎样才能永远运行一个函数?
- ios - iOS Swift 共享 PDF 文件,然后删除
- javascript - 需要 Websocket onMessage 但值未定义
- python-2.7 - lxml解析器在解析html时删除结束标记
- python - django 小部件调整表单控件而不是操作