如果我们将数组对象声明为空,angular2是否支持push函数?

时间:2017-03-15 07:02:06

标签: angular

伙计我已经声明了一个数组对象,如下面的代码所示

 public data: Array<Object> = [] ;

但是,我遇到的真正问题是,当我进行休息api调用时,这个空数组对象会获得一些价值。我试过安慰它。但是在控制台中它显示了

  

[] //清空数组对象

我的其余api调用和forEach循环代码来创建新对象并将其推入已经声明的数组对象

public data: Array<Object>= [] ;

所以,伙计我的休息api和forEach循环代码就在这里,

getChartDetails(examName): void {
this.resultService.getChartDetails(examName).subscribe(response => {
  this.p = response.percentage;
  this.myRes = response.sectionPercentage;
  this.len = response.sections.length;
  this.myRes.forEach(ele => {
    var obj = { value: 0, label: '', percentage: 0, color: "", highlight: "" };
    let dashboardColors = this._baConfig.get().colors.dashboard;
    obj.value = ele.correctedAnswerCount;
    obj.label = ele.sectionName;
    obj.percentage = ele.percentage;
    obj.color = dashboardColors.surfieGreen;
    obj.highlight = colorHelper.shade(dashboardColors.surfieGreen, 15);
    this.data.push(obj);
  });

}) }



 private _loadDoughnutCharts() {
     console.log(this.data);// here i consoled it
    let el = jQuery('.chart-area').get(0) as HTMLCanvasElement;
    console.log(el);
    new Chart(el.getContext('2d')).Doughnut(this.data, {
      segmentShowStroke: false,
      percentageInnerCutout: 64,
      responsive: true
    }); 
 }

 ngAfterViewInit() {
    this.getChartDetails(this.examName);
    if(this.showChart){
      this._loadDoughnutCharts(); 
    }
    if(this.showChart == true){
      this.deleteSession();
    }  
 }

控制台上的实际结果如下图所示 empty array object

控制台上的预期结果应该是这样的

  

[对象,对象,对象,对象,对象,对象,对象,对象,对象]

伙计们帮助我找到解决这个问题的方法。

  

还有一件事来自rest api正确回应

1 个答案:

答案 0 :(得分:1)

我只能在这里做一些猜测。

原因(猜测)

控制台日志显示空this.data,因为在订阅返回数据之前调用了_loadDoughnutCharts()

修复

要解决此问题,请在回调中调用_loadDoughnutCharts()

&#13;
&#13;
getChartDetails(examName): void {
this.resultService.getChartDetails(examName).subscribe(response => {
  this.p = response.percentage;
  this.myRes = response.sectionPercentage;
  this.len = response.sections.length;
  this.myRes.forEach(ele => {
    var obj = { value: 0, label: '', percentage: 0, color: "", highlight: "" };
    let dashboardColors = this._baConfig.get().colors.dashboard;
    obj.value = ele.correctedAnswerCount;
    obj.label = ele.sectionName;
    obj.percentage = ele.percentage;
    obj.color = dashboardColors.surfieGreen;
    obj.highlight = colorHelper.shade(dashboardColors.surfieGreen, 15);
    this.data.push(obj);
  });

  // Call your chart here!!
  this._loadDoughnutCharts();
}) }

private _loadDoughnutCharts() {
 console.log(this.data);// here i consoled it
let el = jQuery('.chart-area').get(0) as HTMLCanvasElement;
console.log(el);
new Chart(el.getContext('2d')).Doughnut(this.data, {
  segmentShowStroke: false,
  percentageInnerCutout: 64,
  responsive: true
});
&#13;
&#13;
&#13;