在 ngOnInit 方法中使用 async/await 会影响生命周期钩子

问题描述 投票:0回答:1

我正在使用 Angular/.Net core 开发一个网站。

我在 ngOnInit() 方法中使用 async/await 来等待结果。

async ngOnInit() {

let response= await this.loginservice.availabilities(this._searchinfo).toPromise();

console.log("no of units");
}

ngAfterViewInit() {

console.log("Call ngAfterViewInit");
}

虽然我使用了await/async,但系统在从ngOnInit()返回结果之前调用了ngAfterViewInit()方法。 这意味着,如果我检查控制台,我可以从控制台看到以下读数

Call ngAfterViewInit
no of units

这怎么可能?使用await/async时,不是会阻塞其他生命周期钩子吗?

提前致谢。

angular asynchronous
1个回答
0
投票

async 只是使 ngOnInit 异步,它会在构造函数的初始化完成后立即运行。

当我们在 ngOnInit 中使用 async 时,它所做的只是允许在函数代码中使用 wait 。它不会导致组件的初始化等待 ngOnInit 完成。

ngOnInit 和 ngAfterViewInit 分别在组件初始化时和 View 组件初始化后调用。所有这些生命周期函数都可以并行运行。单独使用 async/await 无法阻止一个人等待另一个人完成。

如果 ngOnInit 调用中有一个等待,这是可能的。我认为您期待类似“await ngOnInit()”的内容,但在这种情况下,Angular 不会使用 wait 调用 ngOnInit。

我希望这有助于消除您的疑虑。

© www.soinside.com 2019 - 2024. All rights reserved.