![](/img/trans.png)
[英]How to avoid observable delay in angular or make sure my function gets called only when observable is ready
[英]use values from observable in angular when they are ready
我从可观察的获取数据,然后对其进行处理。
我的实际问题是,当我在调用它后使用可观察的数据时,它永远不会到达。
但是当我console.log结果出现在subscribe()
方法中的时候,数据就来了。
我以为Angular在获取数据时会再次调用生命周期钩子,但事实并非如此。
refreshData() {
this.apiService.retrieveIndicatorHistory(this.indicatorName, this.currentPeriod).subscribe(res => {
this.values$.push(res);
console.log("values",res)
});
}
ngOnInit() {
this.refreshData();
... few steps after
console.log("values are here", this.values$); // always empty
}
然后我也尝试在Onchange
显示值,但数据从不打印
ngOnChanges() {
console.log("values are here", this.values$);
// manipulate data
}
准备好从可观察值中获得的值时,如何处理它们? 我是否应该将所有业务逻辑放入subscribe()
?
RxJS Observable以异步方式工作,在接收到数据后将发出一次数据。 因此输入和输出将是可观察的。 为了读取可观察的数据,首先需要订阅它。
refreshData() {
this.apiService.retrieveIndicatorHistory(this.indicatorName, this.currentPeriod).subscribe(res => {
this.values$.push(res);
this.processData();
});
}
ngOnInit() {
this.refreshData();
}
processData(){
console.log(this.values$); // you can access data here.
}
您不应该在订阅中加入业务逻辑。 通常,所有业务逻辑都应放在pipe()中。 您可以使用异步管道在hTML中直接订阅可观察的内容。
因此在html中应该是:
<ul *ngFor="let value of (values$ | async)">
<li>{{value}}</li>
</ul>
在component.ts内部:
values = []
values$ = this.apiService.retrieveIndicatorHistory(this.indicatorName, this.currentPeriod).pipe(
map(res => {
this.values.push(res);
return this.values
})
)
是的,这是一个异步调用,并且订阅将在数据到达时及时知道,ngOnInit中的任何内容都将执行且不会等待。
否则你可以使用(async,await)组合
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.