首页 > 解决方案 > 在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)
  );
}

fooServiceFuncin将fooService一次只返回一个Observable

我的问题是,现在我的应用程序触发了无限请求(在整个数组被迭代之后,它会从头开始,一遍又一遍地再次触发请求),这似乎是这个答案中宣布的管道items的副作用。但我仍然无法弄清楚如何解决这个问题?async

标签: javascriptangulartypescriptasynchronouspipe

解决方案


将您共享的流保存到变量并在模板中使用该变量

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 通过输入流中的每个值运行更改检测)。


推荐阅读