繁体   English   中英

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

[英]Why do I get empty array in ngOnInit after calling a method?

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?



  }

如何获得“订阅”范围之外的数据?

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;
  },
  ...

您会得到想要的号码。

如果要能够将其记录在ngOnInit ,则必须将getHistory方法设置为可观察的。 您可以通过mapmapcatchError而不是订阅来完成此操作,然后返回结果,如下所示:

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);
    });
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM