首页 > 解决方案 > 如何在 AsyncPipe 上使用 trackBy 进行图像渲染,它每次都重新渲染页面?

问题描述

我的问题是如何在 Async 管道上使用 trackby 并在其下渲染图像。

我已经完成了以下操作。在 HTML 中

<div *ngFor="let friend of friends$ | async;trackBy:trackByFn">
  <img [src]="friend.image">
</div>

在我的 component.ts

trackByFn(index, item) {
    if(!item) return null;
    return item && item.id; // or item.id
}

现在的问题是我有一个 2 分钟的计时器,之后我使用 next 语句将新元素推送到friend$ observable

 this.friends$.next(data);

每次我这样做时,我都可以看到对所有图像的请求。并且每张图片都有闪烁效果,为什么?我正在使用 track by 来不重新渲染 dom 元素。

标签: angularngforangularjs-track-by

解决方案


You are pushing a whole new dataset everytime. Try pushing only a new value to your observable, and treat your subject like an array :

friends$ = new BehaviorSubject([]);

add(value) {
  this.friends$.pipe(take(1)).subscribe(items => {
    items.push(value);
    this.friends.next(items);
  });
}

This should automatically resolve your issue, without the need of a track by function.


推荐阅读