Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to use async await with subscribe angular

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

  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();
    }
  }

>Solution :

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();
       }
    }
  }

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading