【问题标题】:use values from observable in angular when they are ready当它们准备好时,使用 angular 中的 observable 值
【发布时间】:2019-07-14 00:47:46
【问题描述】:

我从 observable 获取数据然后对其进行操作。

我的实际问题是,当我在调用后使用 observable 中的数据时,它永远不会到达。

但是当我在subscribe()方法里面的console.log结果一下子数据来了。

我以为 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
}

当我准备好从 observable 获得的值时,我该如何操作它们? 我应该把我所有的业务逻辑都放在subscribe() 中吗?

【问题讨论】:

    标签: javascript angular types rxjs observable


    【解决方案1】:

    您不应该将业务逻辑放在订阅中。一般来说,所有的业务逻辑都应该放在 pipe() 中。您可以使用异步管道直接在 hTML 中订阅 observable。

    所以在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
      })
    )
    

    【讨论】:

      【解决方案2】:

      RxJS Observable 以异步方式工作,它会在收到数据后发出一次。因此输入和输出将是可观察的。为了读取 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.
      }
      

      【讨论】:

        【解决方案3】:

        是的,这是一个异步调用,订阅将准确地知道数据何时到达,ngOnInit 中的任何内容都会执行并且不会等待它。

        否则你可以使用 (async, await ) 组合

        【讨论】:

          猜你喜欢
          • 2020-07-30
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2020-12-07
          • 1970-01-01
          • 2018-12-03
          相关资源
          最近更新 更多