Reputation: 1399
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.
Upvotes: 4
Views: 5720
Reputation: 598728
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();
};
});
Upvotes: 8
Reputation: 4879
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
Upvotes: 1
Reputation: 324
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
}
Upvotes: 2