完成异步函数后调用一个函数

问题描述 投票:0回答:1

我已经看到使用promises一个接一个地调用函数,我有一个带有observable的异步函数。

getHistoryData() {
    this.generatePayload()
    this.historyDataService
      .getHistoryData(this.payload)
      .subscribe(
        (data: any) => {
          const responeData: any = data.dataPoints;
          this.timestampArray = responeData.map(e => e.date.slice(5, 10) + ' ' + e.timestamp.slice(0, 5));
          console.log('temp array' + this.temperatureArray)
          this.temperatureArray = responeData.map(e => e.parameter1 / 100);
          this.dateArray = responeData.map(e => e.date);
        },
      )
  }  
other function is :

 updateChartData(){
  console.log('in update chart data')
  console.log('temp values' + this.temperatureArray)
  this.chartData[0].data =  this.temperatureArray
  this.labels = this.timestampArray
}

我想一个接一个地打电话。怎么做?

angular callback observable subscribe
1个回答
2
投票

solution1:在subscribe()的回调中调用updateChartData():

getHistoryData() {
this.generatePayload()
this.historyDataService
  .getHistoryData(this.payload)
  .subscribe(
    (data: any) => {
      updateChartData();         
    },
  )
}

解决方案2:使用switchMap(),可以访问switchMap中的数据:

getHistoryData() {
  this.generatePayload()
  this.historyDataService
    .getHistoryData(this.payload)
    .subscribe(
      (data: any) => {}
    .switchMap((data) => {
      updateChartData();
    })
  )
© www.soinside.com 2019 - 2024. All rights reserved.