Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/angular/33.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 在firebase中将catch()与.on()一起使用时出错_Javascript_Angular_Firebase_Firebase Realtime Database - Fatal编程技术网

Javascript 在firebase中将catch()与.on()一起使用时出错

Javascript 在firebase中将catch()与.on()一起使用时出错,javascript,angular,firebase,firebase-realtime-database,Javascript,Angular,Firebase,Firebase Realtime Database,我正在使用以下代码检索firebase中的数据: this.managerList = this.afDB.database.ref('users').orderByChild('managedby').equalTo(uID); this.managerList.on('value', (snapshot) => { this.managerIdArray = Object.keys(snapshot.val()); this.manage

我正在使用以下代码检索firebase中的数据:

  this.managerList = this.afDB.database.ref('users').orderByChild('managedby').equalTo(uID);
      this.managerList.on('value', (snapshot) => {
        this.managerIdArray = Object.keys(snapshot.val());
        this.managerNameArray = snapshot.val();
       });
无论何时返回空值,我都会得到一个错误: 错误:未捕获(承诺中):TypeError:无法读取属性。。。。。。。。。。。。未定义的


当我尝试向上面添加catch()时,它说不能使用catch()或then()。如何使用catch()获取错误。

try catch应按以下方式实现:, 您是否可以使用导致错误的trycatch粘贴代码:

try {
  this.databaseService.saveCodesToFirebase(jsonFromCsv)
    .then(result => {
      this.alertService.alertPopup('Success', 'Code Updated')
    })
    .catch(error => {
      this.errorMessage = 'Error - ' + error.message
    })
} catch (error) {
  this.errorMessage = 'Error - ' + error.message
}

您可以查看try/catch的文档:

非常奇怪的是,快照为null,它肯定应该是一个对象,但您也可以在回调中检查它:

this.managerList.on('value', (snapshot) => {
  if (snapshot === null) {
    console.log('some error');
  } else {
    this.managerIdArray = Object.keys(snapshot.val());
    this.managerNameArray = snapshot.val();
  }
});
另外:您能否提供整个错误“TypeError:无法读取未定义的属性……”。哪些属性无法访问?看起来“this”的用法不在这里

Firebase的
on()
方法将侦听器附加到数据,然后该侦听器使用当前值触发一次,每次值更改时都会触发一次。这意味着您的回调可以被调用多次。由于承诺只能解决或失败一次,上的
不会返回承诺

看起来您的查询现在没有返回任何结果,因此
snapshot.val()
返回null。然后
Object.keys(null)
抛出一个错误。 所以类似这样的东西更接近:

this.managerList = this.afDB.database.ref('users').orderByChild('managedby').equalTo(uID);
this.managerList.on('value', (snapshot) => {
  if (snapshot.exists()) {
    this.managerIdArray = Object.keys(snapshot.val());
    this.managerNameArray = snapshot.val();
  };
});
this.managerList = this.afDB.database.ref('users').orderByChild('managedby').equalTo(uID);
this.managerList.on('value', (snapshot) => {
  if (snapshot.exists()) {
    this.managerIdArray = Object.keys(snapshot.val());
    this.managerNameArray = snapshot.val();
  };
});