【问题标题】:Why does ngOnChanges take time. Is it asynchronous?为什么 ngOnChanges 需要时间。是异步的吗?
【发布时间】:2021-09-19 04:25:33
【问题描述】:

我使用的是 Angular 9+,我对 ngOnChanges 生命周期的行为有点困惑。

我要做什么

我有一个异步操作,它使用 @Input() 装饰器为子组件设置一个值(对象类型)。代码如下。 (StackblitzHere)

parent.ts

import { AfterViewInit, Component, VERSION, ViewChild } from '@angular/core';
import { ChildComponent } from './child/child.component';
import { of } from 'rxjs';
import { delay } from 'rxjs/operators';

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent implements AfterViewInit {
  @ViewChild(ChildComponent) childComponent: ChildComponent;
  data = { value: null };

  constructor() {}

  ngAfterViewInit() {
    const foo = of([1])
      .pipe(delay(500))
      .subscribe(subscriber => {
        this.data = { value: 123 };
        this.childComponent.printState();
      });
  }
}

Parent.Html

<app-child [data]="data"></app-child>

子组件

    import { Component, Input, OnChanges } from '@angular/core';

@Component({
  selector: 'app-child',
  templateUrl: './child.component.html',
  styleUrls: ['./child.component.css']
})
export class ChildComponent implements OnChanges {
  @Input() data = null;

  constructor() {}

  ngOnChanges(changes) {
    console.log('ngOnChanges');
  }

  printState() {
    console.log('printState');
    console.log(this.data.value);
  }
}

我想要的是,一旦我更改了值,我就会尝试使用上面显示的视图子引用来打印设置值的值。

理想的顺序应该是

ngOnChanges // initial value
ngOnChanges // after value set
printState // after calling printState()

但我明白

ngOnChanges 
printState 
ngOnChanges

在相当混乱的控制台中。为什么 ngOnChanges 也没有立即被解雇。为什么要花时间。谁能解释一下。

谢谢,注意安全:)

【问题讨论】:

    标签: angular angular9 angular10


    【解决方案1】:

    当您更新绑定到 @Input() 的任何变量时,就像在 ngAfterViewInitAppComponent 中所做的那样,Angular 将安排更改检测仅在 before view rendering 运行,而不是在分配后立即运行。

    因此,ngAfterViewInit 中的代码将首先执行,ngOnChanges 中的代码将在下一个滴答中被 Angular 调用。

    是的,总而言之,变更检测是异步的。

    【讨论】:

    • 为什么必须安排 ngOnChanges ?我认为只有异步代码被安排。 ngOnChanges 不应该是同步的吗?
    • 更新了我的答案 - 是的,ngOnChanges 代码由 Angular 异步执行。
    • 这是有道理的。谢谢你:)
    猜你喜欢
    • 2020-09-12
    • 2016-05-20
    • 2023-04-10
    • 1970-01-01
    • 2015-04-05
    • 1970-01-01
    • 2017-10-26
    相关资源
    最近更新 更多