javascript - Angular 8 : why execution of getcartorCreate() method break after execute the this.id = await this.getServer();
问题描述
private getServer()
{
return this.db.list('/shopping-carts/').snapshotChanges().toPromise();
}
private async getOrCreateCartId() //to create a cartid or acceess the cartid
{
let cartId = localStorage.getItem('cartId'); //to create a cartid or acceess the cartid
if(cartId)
{
return cartId;
}
this.id = await this.getServer();
console.log(this.id);
console.log(this.cartIdFire);
if(this.cartIdFire)
{
return this.cartIdFire;
}
return "return something for testing";
}
after calls the getServer() angular drops the execution of this service even the method getorCreated() is not completed or console.log(this.id); is not printed nothing on console and return nothing totaly dropped the service. what kind of behaviour of this ?
解决方案
because toPromise() is also a rxjx library function,so toPromise wait until the observable fully resolved. But snapshotChanges() continuously sending data and we are awaiting getserver(). so before toPromise() resolved angular suspend the getorCreted() method because it is async and the other dependent methods also not called , to avoid this Mr robert suggested this return this.db.list('/shopping-carts/').snapshotChanges().pipe(take(1)).toPromise(); and this working fine, this pipe(take(1)) method take the value from the observable and unsubscribe observable then toPromise wrap that result into another promise and returns.
推荐阅读
- oracle - Oracle ORA-2291 未找到父键
- java - 获取.xls工作表中单元格的文本和背景颜色为java中的十六进制
- asp.net-mvc - ASP.NET MVC 分页在 ViewModel 上不起作用
- bash - 具有多个条件的 sed 或 awk
- java - 如何使用 poi 根据数据值有条件地设置条形图的颜色
- angular - 在“ng2-smart-table”中编辑或输入数据时验证
- blockchain - Plasma MVP 参数失败/错误
- c# - 带有实体框架错误的 C# Windows 窗体应用程序:System.Data.Entity.Core.ProviderIncompatibleException
- oracle - Oracle APEX - 模式页面中的 Shuttle 值不可用
- jsp - 如何使用 Servlet 中的 for 循环将 getParameterValues("") 存储到数组列表中?