简体   繁体   English

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

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

I have a simple component which holds a BehaviorSubject .我有一个包含BehaviorSubject的简单组件。 In my template I use async pipe to update the view and get the latest value from my BehaviorSubject .在我的模板中,我使用async pipe 来更新视图并从我的BehaviorSubject获取最新值。

When the value is emitted from OnInit lifecycle hook, the async pipe updates the view with the correct value.当值从OnInit生命周期钩子发出时, async pipe 使用正确的值更新视图。 But when I try to emit a value from AfterViewInit , the async pipe does not update the view.但是当我尝试从AfterViewInit发出一个值时, async pipe 不会更新视图。

Is this correct behavior?这是正确的行为吗? Why async pipe won't update the second emitted value?为什么async pipe 不会更新第二个发出的值?

Example component:示例组件:

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

Example component template:示例组件模板:

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

You are using OnPush change detection strategy.您正在使用OnPush更改检测策略。 You should trigger check for changes manually:您应该手动触发检查更改:

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

ngOnInit is called before a view is checked.在检查视图之前调用ngOnInit so 100 will be displayed at first.所以首先会显示100

ngAfterViewInit is called after an initial check for your view has been done. ngAfterViewInit在对您的视图进行初始检查后被调用。 Since you are using OnPush change detection strategy, it will not trigger a change automatically.由于您使用的是OnPush更改检测策略,因此它不会自动触发更改。

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

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