gpt4 book ai didi

angular - 为什么 ngOnChanges 需要时间。是异步的吗?

转载 作者:行者123 更新时间:2023-12-04 07:24:15 26 4
gpt4 key购买 nike

我正在使用 Angular 9+,我对 ngOnChanges 生命周期的行为有点困惑。
我想做的
我有一个异步操作,它使用 @Input() 装饰器为子组件设置一个值(对象类型)。代码如下。 (Stackblitz Here)
父.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();
});
}
}
父.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);
}
}
我想要的是,一旦我更改了值,我就会尝试通过使用 View 子引用来打印设置值的值,如上所示。
理想情况下,序列应该是
ngOnChanges // initial value
ngOnChanges // after value set
printState // after calling printState()
但我明白了
ngOnChanges 
printState
ngOnChanges
在控制台中,这非常令人困惑。为什么 ngOnChanges 也没有立即被解雇。为什么要花时间。有人可以解释一下。
谢谢并保持安全:)

最佳答案

当您更新任何绑定(bind)到 @Input() 的变量时正如你在 ngAfterViewInit 中所做的那样的 AppComponent ,更改检测将由 Angular 安排运行 before view rendering而不是在分配后立即。
因此,ngAfterViewInit 中的代码将首先执行,ngOnChanges 中的代码将在下一个滴答声中由 Angular 调用。
是的,总而言之,变更检测是异步的。

关于angular - 为什么 ngOnChanges 需要时间。是异步的吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68306103/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com