[英]Infinite loop when using *ngFor with async pipe in Angular
我的问题与此非常相似。
在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
中的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>
现在,您为每个item
创建新的流,并且每个查询运行更改检测,Whitch再次运行查询。
我的建议:尽量避免模板中的函数调用,当当前组件运行changeDetection时,模板中的函数会执行(通过输入流中的每个值检测AsyncPipe运行更改)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.