繁体   English   中英

Angular - 当 AfterViewInit 发出新值时,异步 pipe 不更新视图

[英]Angular - Async pipe not updating View when AfterViewInit emits a new value

我有一个包含BehaviorSubject的简单组件。 在我的模板中,我使用async pipe 来更新视图并从我的BehaviorSubject获取最新值。

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

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

示例组件:

@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>

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

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

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM