如您所知,订阅是在服务器返回数据时执行的,但订阅代码的外部是同步执行的。这就是为什么
console.log
在它之外被处决。上面的答案可以完成你的工作,但是你也可以使用
.map
和
return observable
如下所示。
假设你是从服务台打电话给它
export class myClass {
myVariable: any;
// calling and subscribing the method.
callingFunction() {
// the console log will be executed when there are data back from server
this.myClass.MyFunction().subscribe(data => {
console.log(data);
});
}
}
export class myClass {
myVariable: any;
// this will return an observable as we did not subscribe rather used .map method
myFunction() {
// use .pipe in case of rxjs 6
return this.myService.getApi().map(data => {
this.myVariable = data;
this.update()
});
}
}