为什么调用方法后在ngOnInit中得到空数组?

时间:2019-04-10 14:51:29

标签: angular typescript

getHistory(gaaNum): void {

this.loading = true;
this.gaaHistoryService.getHistory(gaaNum)
  .subscribe(atmHistory => {
    // I am more sure that real data gets assigned here!!!
    this.allChartData = atmHistory; // allChartData has a size of 152
    this.loading = false;
  }, err => {
    this.loading = false;
    this.errorMsg = err;
    console.log(`error: ${err}`);
  });
}

但是,allChartData公共变量在此处为空:

    ngOnInit() { 
    this.allChartData = [];
    this.amount= [];
    this.fillSum = [];
    this.barChartData = [];

    this.getHistory(this.gaaNumber);

    console.log(this.allChartData.length);  // this is zero, allChartdata is empty here. Why?



  }

如何获取超出“订阅”范围的数据?

2 个答案:

答案 0 :(得分:3)

JavaScript是异步的,因此在编写时

this.getHistory(this.gaaNumber);
console.log(this.allChartData.length);

getHistory()被调用-在没有时间完成之前,您已经在调用console.log(this.allChartData.length),它将因此打印出0。

如果您改写类似

  ...
  this.gaaHistoryService.getHistory(gaaNum)
  .subscribe(atmHistory => {
    // I am more sure that real data gets assigned here!!!
    this.allChartData = atmHistory; // allChartData has a size of 152
    console.log(this.allChartData.length);
    this.loading = false;
  },
  ...

您将得到您想要的号码。

答案 1 :(得分:2)

如果您希望能够将其记录在ngOnInit中,则必须使getHistory方法成为可观察的方法。您可以通过管道传递到mapcatchError中而不是订阅来完成此操作,然后返回结果,如下所示:

getHistory(gaaNum): void {

    this.loading = true;
    return this.gaaHistoryService.getHistory(gaaNum)
      .pipe(map(atmHistory => {
        this.allChartData = atmHistory; 
        this.loading = false;
      }), catchError(err => {
        this.loading = false;
        this.errorMsg = err;
        console.log(`error: ${err}`);
      }));
}

现在,在您的ngOnInit中,您可以订阅getHistory并做您想做的任何事情。

ngOnInit() { 
    this.allChartData = [];
    this.amount= [];
    this.fillSum = [];
    this.barChartData = [];

    this.getHistory(this.gaaNumber).subscribe(_ => { 
        console.log(this.allChartData.length);
    });
}