[英]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.我是 Angular 的新手,我正在努力修复用 Angular 2 编写的东西。在该方法中,我们调用了可观察方法,之后我们为变量赋值。 I need the obersavable method to finish execution before assigning the value.
在分配值之前,我需要 obersavable 方法来完成执行。 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.因此,如上所示,我需要在 getData Observable 方法执行完毕后将 true 分配给 gotData 变量。 But gotData is getting assigned true even before we actually get the data.
但是在我们实际获取数据之前,gotData 就被赋值为 true。
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.听起来你需要阅读 Observables 和 Subscriptions。 Angular Docs
Angular文档
Alternatively, the subscribe() method can accept callback function definitions in line, for next, error, and complete handlers.
或者,subscribe() 方法可以在行中接受回调 function 定义,用于下一个、错误和完成处理程序。 For example, the following subscribe() call is the same as the one that specifies the predefined observer:
例如,以下 subscribe() 调用与指定预定义观察者的调用相同:
In your case the callback you have named res
will be called after your observable method is finished.在您的情况下,您命名为
res
的回调将在您的可观察方法完成后被调用。
So your code could be:所以你的代码可能是:
Method1(): void {
this.Service.getData()
.subscribe(
res => {
this.gotData = true;
},
error => this.errorMessage = <any>error
);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.