首页 > 解决方案 > 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 ?

标签: javascriptangulartypescriptfirebasenodes

解决方案


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.


推荐阅读