我正在尝试从 Firebase 获取数据并将其设置为类中的变量。我面临的问题是变量在 ngAfterViewInit() 中未定义。
我知道它是在 ngOnInit() 中设置的。我已经阅读了 Angular 文档页面中的 Angular 生命周期方法和英雄之旅示例,以查看我是否正确获取了数据,但它仍然无法解释这种奇怪的行为(至少对我而言!)。
ngOnInit() {
this.http.get('https://xxxxxxxx-xxxxx.firebaseio.com/data.json').map(response => response.json())
.subscribe(
data => {
for (var i = 0; i < data.length; i++) {
var a: string = data[i]['date'];
data[i]['date'] = new Date(a);
}
this.timeline = data; // declared in class
this.timelineElements = data; // declared in class
console.log(data); // data is not empty
console.log(TIMELINE); // data is not empty
},
error => {
console.log(error);
}
)}
ngAfterViewInit() {
console.log(this.timeline); // Undefined if fetched from firebase. Works perfectly if the data is fetched locally
}
如果我尝试在本地设置这两个变量,则一切正常。问题是当我尝试从 firebase 获取它时。
我是 Angular 世界的新手,但我的理解是,在我的情况下,
ngAfterViewInit()
在 Firebase 的数据到达之前被调用?虽然不确定。有没有办法解决这个问题?
最佳答案
http.get 是一个异步函数,这意味着它需要时间来完成。在这种情况下 ngAfterViewInit 在 http.get 完成之前被调用。
无论如何,您为什么要使用 ngOnInit 和 ngAfterViewInit 将所有内容分开?
关于angular - ngOnInit() 中的数据集在 ngAfterViewInit() 中未定义,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/46031140/