ngOnInit()中设置的数据在ngAfterViewInit()中未定义 [英] data set in ngOnInit() is undefined in ngAfterViewInit()

查看:336
本文介绍了ngOnInit()中设置的数据在ngAfterViewInit()中未定义的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试从Firebase获取数据并将其设置为Class中的变量.我面临的问题是该变量在ngAfterViewInit()中未定义.

I am trying to get the data from Firebase and set it to a variable in the Class. The problem that I am facing is that the variable is undefined in the ngAfterViewInit().

我知道它是在ngOnInit()中设置的.我已经在Angular文档页面上阅读了Angular生命周期方法和英雄之旅示例,以查看我是否正确获取了数据,但是它仍然不能解释这种奇怪的行为(至少对我来说!).

I know for a fact that it is set in ngOnInit(). I have read up Angular lifecycle methods and the tour of heroes example in the Angular doc page to see if I am fetching the data correctly, but it still does not explain this strange behavior (at least to me!).

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数据到达之前被调用的吗?不确定.

Everything works perfectly fine if I try and set the the two variables locally. The problem is when I try and fetch it from firebase. I am new to Angular world, but my understanding is that maybe in my case, ngAfterViewInit() is invoked way before the data from Firebase arrives? Not sure though.

有没有办法解决这个问题?

Is there a way to fix this?

推荐答案

http.get是一个异步函数,这意味着需要花费一些时间才能完成.在这种情况下,在http.get完成之前将调用ngAfterViewInit.

http.get is an asynchronous function which means it takes time to complete. In this case ngAfterViewInit is called before http.get is completed.

为什么您仍要使用ngOnInit和ngAfterViewInit分隔所有内容?

Why do you want to seperate everything with ngOnInit and ngAfterViewInit anyways?

这篇关于ngOnInit()中设置的数据在ngAfterViewInit()中未定义的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆