Home > front end >  How to use async await with subscribe angular
How to use async await with subscribe angular

Time:08-02

I'm calling createOtherKind() function and trying to use the value of this.listKinds. My problem is that isKindOtherCreated is not waiting this.getKinds() to finish and this.listKinds is undefined.

How can i do it?

Code:

  getKinds(): void {
    this.detailsService.getKinds().subscribe(async response =>{
      this.listKinds = await response.body;
    })
  }

  async createOtherKind() {
    await this.getKinds();
    const isKindOtherCreated = this.listKinds.find(kind => kind.name === "Other");

    if(!isKindOtherCreated) {
      this.createdKind.name = "Other";
      this.createKind();
    }
  }

CodePudding user response:

You can call the createOtherKind() method inside getKinds() method. This is how you will get the value from this.listKinds variable. subscribe is async method. So, it does not wait for the reponse.

Here is Example:

getKinds(): void {
    this.detailsService.getKinds().subscribe(async response =>{
      this.listKinds = response.body;
      await this.createOtherKind();
    })
  }

async createOtherKind() {
    const isKindOtherCreated = this.listKinds.find(kind => kind.name === "Other");

    if(!isKindOtherCreated) {
      this.createdKind.name = "Other";
      this.createKind();
    }
  }

CodePudding user response:

The issue is happening because you're mixing Observables (where you have subscribe) with async/await. If you want to stick to using promises you could revise your getKinds function to something like this:

  getKinds(): void {
    // Convert your observable to a Promise so you can use `await` on it
    return this.detailsService.getKinds().toPromise().then((response) => {
      this.listKinds = await response.body;
    });
  }

For more details, I recommend taking a look at this similar question.

CodePudding user response:

You use subscribe here, so I guess this.detailsService.getKinds() returns an observable. You can make things with it then return it to be able to subscribe something else in another part of your code. like:

getKinds(): Observable<any> {
    let myObs = this.detailsService.getKinds(); //Getting your observable

    //Reading result
    myObs.subscribe(response => {
      this.listKinds = response.body;
    });

    //Returning it to use it somewhere else
    return myObs;
  }

createOtherKind() {
    //Make request and subscribe to observable
    this.getKinds().subscribe( res => {
        const isKindOtherCreated = this.listKinds.find(kind => kind.name === "Other");

        if(!isKindOtherCreated) {
          this.createdKind.name = "Other";
          this.createKind();
       }
    }
  }

  • Related