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
);
}
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments