首页 > 解决方案 > Angular - AfterViewInit 发出新值时,异步管道不更新视图

问题描述

我有一个简单的组件,其中包含一个BehaviorSubject. 在我的模板中,我使用async管道更新视图并从我的BehaviorSubject.

当值从OnInit生命周期钩子发出时,async管道会使用正确的值更新视图。但是当我尝试从中发出一个值时AfterViewInitasync管道不会更新视图。

这是正确的行为吗?为什么async管道不会更新第二个发出的值?

示例组件:

@Component({
  selector: 'app-example',
  templateUrl: './example.component.html',
  changeDetection: ChangeDetectionStrategy.OnPush
})
export class ExampleComponent implements OnInit, AfterViewInit {
  
  public test$ = new BehaviorSubject(0);

  constructor(public cd: ChangeDetectorRef) {
    // All three values are logged - 0, 100, 200
    this.test$.subscribe(console.log);
  }

  ngOnInit() {
    // View is updated with 100 value
    this.test$.next(100);
  }

  ngAfterViewInit() {
    // View is not updated, async pipe is not triggered
    this.test$.next(200);
  }
}

示例组件模板:

<h1>{{ test$ | async }}</h1>

标签: angulartypescript

解决方案


您正在使用OnPush更改检测策略。您应该手动触发检查更改:

ngAfterViewInit() {
    // View is not updated, async pipe is not triggered
    this.test$.next(200);
    this.cd.detectChanges();
}

ngOnInit在检查视图之前调用。所以100会首先显示。

ngAfterViewInit在对您的视图进行初始检查后调用。由于您使用的是OnPush变更检测策略,因此它不会自动触发变更。


推荐阅读