angular - Angular async pipe doesn't trigger change detection
问题描述
I have this class binding which should animate my image while loading, but it never trigger.
<img [class.animated]="loader.isLoading$ | async" src="...">
Loader :
public get isLoading$(): Observable<boolean> {
return this._isLoading$.pipe(
// If the data arrives successfully earlier than in 250ms, no indicator should be shown
switchMap(isLoading => isLoading ? of(true).pipe(delay(250)) : of(false))
);
}
Using vanilla javascript works (so I guess the Loader code is fine) :
ngAfterViewInit(): void {
this.loader.isLoading$.subscribe(
isLoading => {
const img = document.querySelector('img') as HTMLImageElement;
if (isLoading) {
img.classList.add('animated');
}
else {
img.classList.remove('animated');
}
}
);
}
edit : The class binding works without the delay(250)
, why ?
Where am I doing wrong with the class binding ? Even with ChangeDetectionStrategy.Default
it doesn't work.
Thanks for any explanation.
解决方案
isLoading$()
是一个吸气剂,因此每次触发更改检测周期时都会调用它,它将返回一个新的 RxJS 链。async
将从前一个取消订阅并订阅新的(可能会在this._isLoading$
再次发出后发出)。
所以只保留一条链子。isLoading$()
也许在你的组件中使用一个局部变量。
推荐阅读
- angular - 如何在 Jasmine 单元测试中订阅 Observable?
- c# - 如何在 shell 上打印 C# 列表中的项目?
- angular - 如何在组件中使用来自 UrlMatcher 的 Angulars 路由 UrlMatchResult?
- postscript - 如何在不使用 PostScript 中滚动的情况下将堆栈顶部的数字移动到底部?
- visual-c++ - 如何在对话框中将派生的 CStatic 分配给现有优化校准
- c# - System.Threading.Timer async - 将定时器线程上的更新合并回主线程
- mysql - mysql:更新/添加到同一个表中的列
- reactjs - 获取背景颜色以更改的问题
- node.js - 在 Node JS 文件中包含 Native Prototype 扩展
- javascript - 如何通过单击按钮更改图像?