我从可观察的数据中获取数据,然后对其进行操作。
我的实际问题是,当我在调用它之后使用来自 observable 的数据时,它永远不会到达。
但是当我在 subscribe()
方法中 console.log 结果时,数据就会出现。
我以为 Angular 在获取数据时会再次调用生命周期钩子(Hook),但事实并非如此。
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
}
当 observable 准备好时,我如何操作它们获得的值?
我应该将所有业务逻辑放在 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.
}
关于javascript - 准备好后,使用 Angular 中可观察到的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54784482/