【发布时间】:2021-06-25 04:26:20
【问题描述】:
我想在ngOnInit() 之后执行一些逻辑,因为我想将逻辑与页面渲染分离。
我想到了 Angular 生命周期钩子,所以我将逻辑放在 ngAfterViewInit() 中,但似乎它与 ngOnInit() 同时被调用。
代码示例:
export class SampleComponent implements OnInit, AfterViewInit{
list = [];
ngOnInit() {
this.localDataService.getData().then( res =>{ //Promise call
for (let o in res) {
this.list.push(res[o]) //the list get loaded
})
}
ngAfterViewInit() { // the intention is to process the list after it's loaded
this.remoteDataService.getData().then(res => {
for (let o in res) {
itemFound = this.list.find( (itemInList) => {return itemInList.id === res[o].id})
//and some code to manipulate the item found from list
itemFound = .... // but the itemFound is always 'undefined'
})
}
}
根据 Angular 生命周期钩子,ngAfterViewInit() 应该在ngOnInit() 之后执行,但代码运行结果表明并非如此。 ngAfterViewInit() 中的 itemFound 始终为“未定义”。
我尝试将代码块从ngAfterViewInit() 放到ngOnInit(),在promise 调用之后,
itemFound 将获得适当的价值。
谁能帮忙解释哪里出错了?是不是因为 Promise 调用是异步的?
【问题讨论】:
-
为什么不创建一个简单的函数并在 getData() 承诺中调用它?
-
我所做的和你提到的完全一样,但我发现
remoteDataService.getData()的承诺会显着影响页面渲染速度,因为它是一个远程调用并且需要很多时间。这就是我想将它们解耦的原因。
标签: angular promise sequence angular-lifecycle-hooks