我想在之后执行一些逻辑,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()
,但代码运行结果表明并非如此。itemFound
inngAfterViewInit()
始终是“未定义的” 。
我试图将代码块从ngAfterViewInit()
to ngOnInit()
,在 promise 调用之后,itemFound
将获得适当的值。
谁能帮忙解释哪里出了问题?是因为 Promise 调用是异步的吗?