在不将 snapshotChanges() 转换为 promise 的情况下,此方法的任何解决方法?
Any workaround for this method without convert snapshotChanges() into promise?
我想 return cartIdFire 但它 return 未定义,因为快照方法 return 可观察
所以,对于 returning cartIdFire 没有将快照方法转换为 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;
}
所以我无法通过 getServer() 方法 return 订阅者。因为我要存钱
本地存储中的 cartFireId。
这种场景下,await this.getServer()
就不行了,不会等着解决,只在Promise中有效,在Observable中不行,在subscribe中解决
一个简单的解决方案是,在 getServer()
方法中将 Observable 转换为 Promise,使用 toPromise()
并返回此值
private async getServer()
{
return this.db.list('/shopping-carts/').snapshotChanges().toPromise()
}
并在getOrCreateCartId()
方法中得到cartIdFire
this.cardIdFire = await this.getServer()
我想 return cartIdFire 但它 return 未定义,因为快照方法 return 可观察
所以,对于 returning cartIdFire 没有将快照方法转换为 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;
}
所以我无法通过 getServer() 方法 return 订阅者。因为我要存钱
本地存储中的 cartFireId。
这种场景下,await this.getServer()
就不行了,不会等着解决,只在Promise中有效,在Observable中不行,在subscribe中解决
一个简单的解决方案是,在 getServer()
方法中将 Observable 转换为 Promise,使用 toPromise()
并返回此值
private async getServer()
{
return this.db.list('/shopping-carts/').snapshotChanges().toPromise()
}
并在getOrCreateCartId()
方法中得到cartIdFire
this.cardIdFire = await this.getServer()