Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
283 views
in Technique[技术] by (71.8m points)

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 ?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...