javascript - 在Angular中将*ngFor与异步管道一起使用时的无限循环
问题描述
我的问题与这个非常相似。
在foo.component.html
:
<ng-container *ngFor="let item of items">
<ng-container *ngIf="(fooFunc(item.property) | async) as element">
{{ element | json }}
</ng-container>
</ng-container>
在foo.component.ts
:
fooFunc(foo: any) {
return this.fooService.fooServiceFunc(foo).pipe(
take(1),
shareReplay(1)
);
}
fooServiceFunc
in将fooService
一次只返回一个Observable
。
我的问题是,现在我的应用程序触发了无限请求(在整个数组被迭代之后,它会从头开始,一遍又一遍地再次触发请求),这似乎是这个答案中宣布的管道items
的副作用。但我仍然无法弄清楚如何解决这个问题?async
解决方案
将您共享的流保存到变量并在模板中使用该变量
data$ = forkJoin(
this.items.map(item => this.fooService.fooServiceFunc(item.property).pipe(
map(fetchResult => ({ fetchResult, item })
))
)
<ng-container *ngFor="let item of data$ | async">
<ng-container *ngIf="item.fetchResults">
{{ item.fetchResults | json }}
</ng-container>
</ng-container>
现在您为 each 创建新的流item
,并且每个查询运行更改检测,然后再次运行查询。
我的建议:尽量避免模板中的函数调用,模板中的函数在当前组件的 changeDetection 运行时执行(AsyncPipe 通过输入流中的每个值运行更改检测)。
推荐阅读
- laravel - 枚举值在 Livewire 上验证
- mongodb - 如何使用 mapreduce 计算 MongoDB 中的相同值?
- python - 附加 csv,不覆盖
- r-markdown - 如何修复 R markdown 中的 row_to_name 错误?
- php - 如何在 Wordpress 中突出显示文本?
- html - 单选按钮被隐藏,不会显示
- python - 在 django rest 响应中删除额外的双引号
- go - 尝试使用 go-swagger 生成的 api 服务器实现 qor 仪表板时出现服务器恐慌
- node.js - MongoDB:查找具有相同键值的文档集
- javascript - 将函数转换为异步函数而不重新定义