角度异步管道不会触发更改检测

时间:2021-07-03 08:45:29

标签: angular rxjs angular-changedetection async-pipe

我有这个类绑定,它应该在加载时为我的图像设置动画,但它永远不会触发。

<img [class.animated]="loader.isLoading$ | async" src="...">

加载器:

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))
    );
  }

使用 vanilla javascript 有效(所以我猜 Loader 代码很好):

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 :类绑定在没有 delay(250) 的情况下工作,为什么?

我在类绑定上做错了什么?即使使用 ChangeDetectionStrategy.Default 它也不起作用。

感谢您的解释。

1 个答案:

答案 0 :(得分:1)

isLoading$() 是一个 getter,因此每次触发更改检测周期时都会调用它,并返回一个新的 RxJS 链。 async 将取消订阅前一个并订阅新的(可能会在 this._isLoading$ 再次发出后发出)。

所以只保留一条链。也许在你的组件中使用 isLoading$() 创建一个局部变量。

相关问题