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

时间:2019-05-17 13:29:40

标签: javascript angular typescript asynchronous pipe

我的问题与this one非常相似。

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数组被迭代之后,它将从头开始一遍又一遍地再次激发该请求),这似乎是一个副作用this answer中宣布的async管道。但是我仍然不知道该如何解决?

1 个答案:

答案 0 :(得分:2)

将共享流保存为变量并在模板中使用变量

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创建新的流,并且每个查询运行更改检测,再次运行查询。

我的建议:尽量避免模板中的函数调用,当当前组件运行changeDetection时,模板中的函数会执行(通过输入流中的每个值检测AsyncPipe运行更改)。

相关问题