javascript - 准备好后,使用 Angular 中可观察到的值

标签 javascript angular types rxjs observable

我从可观察的数据中获取数据,然后对其进行操作。

我的实际问题是,当我在调用它之后使用来自 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/

相关文章:

string - 将整数转换为lua中的字符串?

java - 使用 ajax 从浏览器发送到基于 java 的服务器的最佳数据格式?

angular - 空注入(inject)器错误 : No provider for _CoalescedStyleScheduler

node.js - Angular2 POST Observable 请求返回不可读的 JSON 对象

javascript - 即使从数据列表中选择选项也会触发响应式(Reactive)表单的 valueChanges 事件

c# - 为什么具体化的泛型很难与更高级的类型结合使用?

go - 无需接口(interface)即可将多种类型合二为一

javascript - 如何获取2个字符串之间的字符串

javascript - 是否可以使用 JSON 对象在 jq 中进行嵌套查询?

javascript - 如何在 React JS 中为 div 动态设置类名