简体   繁体   English

在Angular中将* ngFor与异步管道一起使用时出现无限循环

[英]Infinite loop when using *ngFor with async pipe in Angular

My problem is very similar to this one . 我的问题与非常相似。

In foo.component.html : 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>

In foo.component.ts : foo.component.ts

fooFunc(foo: any) {
  return this.fooService.fooServiceFunc(foo).pipe(
    take(1),
    shareReplay(1)
  );
}

The fooServiceFunc in fooService will return only one Observable at one time. fooServiceFunc中的fooService将仅返回一个Observable

My problem is that now my app fires infinite requests (after the whole items array has been iterated, it will fire the request again from beginning, over and over), which seems to be a side-effect of async pipe which is announced in this answer . 我的问题是,现在我的应用程序触发了无限请求(在迭代了整个items数组之后,它将从头开始一遍又一遍地再次触发该请求),这似乎是在声明的async管道的副作用回答 But I still cannot figure out how to fix this? 但是我仍然不知道该如何解决?

Save you shared stream to variable and use the variable in template 将共享流保存到变量并在模板中使用变量

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>

Now you create new stream for each item , and each query runs change detection, whitch runs queries again. 现在,您为每个item创建新的流,并且每个查询运行更改检测,Whitch再次运行查询。

My advice: Try to avoid function calls in templates, functions in template executes when changeDetection for current component runs (AsyncPipe run change detection by each value in the input stream). 我的建议:尽量避免模板中的函数调用,当当前组件运行changeDetection时,模板中的函数会执行(通过输入流中的每个值检测AsyncPipe运行更改)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM