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

最佳答案

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

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运行更改)。

关于javascript - 在Angular中将* ngFor与异步管道一起使用时出现无限循环,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/56187470/

10-10 00:24
查看更多