angular - 如何在 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 元素。
解决方案
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.
推荐阅读
- json - 通过正则表达式查找密钥的 Json 路径
- excel - 为什么我的 IF 函数不能将单元格中的所有值都带入
- jqplot - 为什么图形渲染在 chrome 中显示不好?
- postgresql - 使用 shells 脚本将 csv 数据导入 postgres
- ios - 尝试将 Flutter 添加到 iOS 应用程序时,命令 PhaseScriptExecution 失败,退出代码非零
- swift - 嵌套的 UITableViewDataSource 不调用 cellForRowAt:
- php - 如何修复错误:在 laravel 中调用 null 上的成员函数 getPathName()?
- android - 在 android studio 中无休止的安装
- node.js - nodejs项目中的MongoDB 4.2 maxIdleTimeMS
- python - 在 Plotly 图表标题(Python)中使用多种字体大小