【问题标题】:how to resolve the ''cannot read property 'property-name' of null?如何解决''无法读取属性'property-name'为null?
【发布时间】:2017-12-02 15:39:15
【问题描述】:

我正在尝试将 firebase 数据库中的所有数据检索到 typescript 中的数组中。以下是相关代码 sn -p :

export class ViewUserPage {
  public list = [];
  public ref = firebase.database().ref();
  public usersRef = this.ref.child('users');

  constructor(public navCtrl: NavController, public navParams: NavParams) {}
  
  ionViewDidLoad(){
  
  this.usersRef.orderByChild('tag').equalTo('staff').on('child_added',function(snap){
    this.list.push(snap.val());console.log(snap.val());
    });

}

   

}

我得到的错误是“无法读取 null 的属性 'list'”。我认为它发生在

this.usersRef.orderByChild('tag').equalTo('staff').on('child_added',function(snap){
    this.list.push(snap.val());console.log(snap.val());

部分。这是完整的错误:

ERROR TypeError: Cannot read property 'list' of null
    at main.js:59030
    at main.js:30999
    at fc (main.js:30861)
    at bf (main.js:30926)
    at cf (main.js:30925)
    at Qg.g.Gb (main.js:31016)
    at Ag.g.wd (main.js:30980)
    at og.wd (main.js:30970)
    at Yf.Xf (main.js:30968)
    at ag (main.js:30952)
defaultErrorLogger @ main.js:1436 

如何解决这个问题?请帮忙!

【问题讨论】:

  • 可以粘贴你的 html 你在哪里使用模板中的列表变量?
  • 添加您的完整错误图像,其中可能包括函数名称或与错误相关的任何其他内容
  • @RahulSingh 我还没有在 html 中使用列表数组。这里我只是想将元素存储在数组中。

标签: angular typescript firebase ionic-framework firebase-realtime-database


【解决方案1】:

您正在使用 function 关键字创建新范围并更改 this 的值,您应该使用胖箭头函数而不是更改 this 的值,但根据您的 cmets firebase似乎为this 绑定了另一个值,因此您需要将this 的值存储在另一个变量中,如下所示:

let that = this;
this.usersRef.orderByChild('tag').equalTo('staff').on('child_added', (snap) => {
    that.list.push(snap.val());
    console.log(snap.val());
});

【讨论】:

  • 这在一定程度上起作用,因为前面的错误得到了解决。现在我收到一个新错误,上面写着:'' TypeError: Cannot read property 'push' of undefined '' 。我该如何解决这个问题?
  • 也许firebase正在改变this的值,所以我将this的值存储在另一个变量that中,我已经编辑了我的答案,让我知道这个新解决方案是否有效跨度>
  • 你确认public list = []; 仍然存在于你的代码中
  • 我已将其更改为“public list:string[];”因此它不起作用。当我把它改回来时,它起作用了!知道为什么会这样吗?
  • 当你写public list: string[]; 时,它只是告诉打字稿,将来这个变量将保存一个字符串数组,但值仍然是undefined。你需要做的是像这样初始化一个空数组:public list: string[] = [];
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-09-28
  • 2019-12-03
  • 2018-08-03
  • 1970-01-01
  • 2022-01-26
  • 2019-04-30
  • 1970-01-01
相关资源
最近更新 更多