I have developed a provider specifically for handling all Firebase database related requests. In the getUser method, when the data is fetched from the database using .once which returns a promise, if the object is null it currently returns null. This means I need to handle this at the page level as shown below:
ngOnInit() {
this.dbcon.getUser().then(dbvalue=>{
if(dbvalue.val()){
//..do something..
}
});
Instead of returning null, I would prefer the provider to return a valid object or something like {sorcode:''}. Any suggestions on achieving this at the provider level are appreciated.
When I tried to implement this logic in the provider to return a hardcoded object {sorcode:''} in case of null, it still returns null.
Code snippet on the page:
ngOnInit() {
this.dbcon.getUser().then(dbvalue=>{
console.log(dbvalue.val());
});
}
Provider code (note that .once is a promise):
getUser()
{
return firebase.database().ref(`/users/`).once('value', dataSnapshot => {
if (dataSnapshot.val()==null)
{
{sorcode:''};
}
else
{
dataSnapshot.val();
}
});
}
By placing the 'return' keyword within the IF loop and not before calling the promise as shown below, it throws an error on the page: "Cannot read property 'then' of undefined"
Provider code example:
getUser()
{
firebase.database().ref(`/users/`).once('value', dataSnapshot => {
if (dataSnapshot.val()==null)
{
return {sorcode:''};
}
else
{
return dataSnapshot.val();
}
});
}
Even by adding the 'return' keyword within the IF loop and also before calling the promise, as shown below, the original issue persists - it returns null when the object does not exist.
Provider code excerpt:
getUser()
{
return firebase.database().ref(`/users/`).once('value', dataSnapshot => {
var x=dataSnapshot.val();
if (x==null)
{
return {sorcode:''};
}
else
{
return dataSnapshot.val();
}
});
}