简体   繁体   中英

How to wait for a observable method to finish before proceeding in Angular 2

I am new to Angular and I am working on fixing something that is written in Angular 2. In the method we have a call to to observable method after that we are assigning a value to a variable. I need the obersavable method to finish execution before assigning the value. Given below is the code for your reference.

Method1(): void {
     this.Service.getData()
        .subscribe(
        res => {
          
        },
        error =>  this.errorMessage = <any>error);
        this.gotData = true;
}

So, As shown above, I need to assign true to gotData variable after the getData Observable method is finished execution. But gotData is getting assigned true even before we actually get the data.

Please help me who to wait until the observable method is finished execution. Thank you !

Sounds like you need to read up on Observables and Subscriptions. Angular Docs

Alternatively, the subscribe() method can accept callback function definitions in line, for next, error, and complete handlers. For example, the following subscribe() call is the same as the one that specifies the predefined observer:

In your case the callback you have named res will be called after your observable method is finished.

So your code could be:

Method1(): void {
     this.Service.getData()
        .subscribe(
        res => {
          this.gotData = true;
        },
        error =>  this.errorMessage = <any>error
       );

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM