使用 *ngfor与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)
  );
}

fooService中的fooServiceFunc一次仅返回一个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创建新流,每个查询运行更改检测,再次运行查询。

我的建议:尝试避免使用模板中的函数调用,模板中的函数在当前组件运行时执行(asyncpipe run run run更改检测通过输入流中的每个值(。

最新更新