简体   繁体   中英

Error using catch() with a .on() in firebase

I am retrieving data in firebase using the following code:

  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();
       });

Whenever a null value is returned, I get an error : Error: Uncaught (in promise): TypeError: Cannot read property............ of undefined.

When I try to add a catch() to the above, it says cannot use catch() or then(). How do I use a catch() to take error.

Firebase's on() method attaches a listener to the data, which then fires once with the current value and each time the value changes. This means your callback can get called multiple times. Since a promise can only resolve or fail once, on does not return a promise.

It looks like your query does not return any result right now, so snapshot.val() returns null. And then Object.keys(null) throws an error. So something like this is closer:

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();
  };
});

try catch shuld be implemented as following , can you paste your code with trycatch that cause the error:

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
}

you could just check the documentation of try/catch: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/try...catch

try {
  this.managerList.on('value', (snapshot) => {
    this.managerIdArray = Object.keys(snapshot.val());
    this.managerNameArray = snapshot.val();
  });
} catch (someError) {
  console.log('got some error: ', someError);
}

it is very strange, that the snapshot is null, it should definitely be an object, but you can also check it inside your callback:

this.managerList.on('value', (snapshot) => {
  if (snapshot === null) {
    console.log('some error');
  } else {
    this.managerIdArray = Object.keys(snapshot.val());
    this.managerNameArray = snapshot.val();
  }
});

Also: can you provide the whole error " TypeError: Cannot read property............ of undefined." What property can not be accessed? It looks like your use of "this" is not right here

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM