I want to return cartIdFire but it returns undefined because snapshot method is return observable
so, there is any workaround for returning cartIdFire without convert snapshot method into promise ?
private async getServer()
{
this.db.list('/shopping-carts/').snapshotChanges()
.subscribe(x => this.cartIdFire = x);
return cartIdFire;
}
private async getOrCreateCartId() //to create a cartid or acceess the cartid
{
let cartId = localStorage.getItem('cartId'); //to create a cartid or acceess
if(cartId)
{
return cartId;
}
this.id = await this.getServer();
console.log(this.id);
console.log(this.cartIdFire); //it gives undefined
if(this.cartIdFire)
{
localStorage.setItem('cartId' ,result.key);
return this.cartIdFire;
}
let result = await this.create();
localStorage.setItem('cartId' ,result.key);
return result.key;
}
so i can't return subscriber from getServer() method. Because i have to save
the cartFireId in the local storage.
In this scenario, await this.getServer()
will not work, it will not wait to be solved, it only works in Promise, not in Observable, where it is solved within the subscribe
A simple solution would be, in the getServer()
method to convert the Observable to Promise, using toPromise()
and returning this value
private async getServer()
{
return this.db.list('/shopping-carts/').snapshotChanges().toPromise()
}
And get the cartIdFire
in the getOrCreateCartId()
method
this.cardIdFire = await this.getServer()