第一次不填充数组

时间:2019-10-03 18:28:08

标签: angular multidimensional-array

在调用此函数时,supplypayment和supplyBrand数组首次没有值

this.getSupply().subscribe (list => {
      let array = list.map(item =>{
        return {
          $key: item.key,
          ...item.payload.val()
        };
      });
      array.forEach(element => {
        this.supplypayment.push(element.payment);
        this.supplyBrand.push(element.BrandName);
      });

    }

supplyPayment和supplyBrand在控制台的图表中使用,supplyPayment和supplyBrand未定义或初始化值。但是当第二次调用同一图形组件时,它可以正常工作!

ngOnInit() {
    this.BarChart = new Chart('barChart2', {

      type: 'bar',
    data: {
     labels:this.x,
     datasets: [{
         label: 'Payment',
         data  :  this.serv.supplypayment,
         backgroundColor: [
             'rgba(255, 99, 132, 0.2)',
             'rgba(54, 162, 235, 0.2)',
             'rgba(255, 206, 86, 0.2)',
             'rgba(75, 192, 192, 0.2)',
             'rgba(153, 102, 255, 0.2)',
             'rgba(255, 159, 64, 0.2)'
         ],
         borderColor: [
             'rgba(255,99,132,1)',
             'rgba(54, 162, 235, 1)',
             'rgba(255, 206, 86, 1)',
             'rgba(75, 192, 192, 1)',
             'rgba(153, 102, 255, 1)',
             'rgba(255, 159, 64, 1)'
         ],
         borderWidth: 1
     }]
    }, 
    options: {
     title:{
         text:this.serv.supNamerep,
         display:true
     },
     scales: {
         yAxes: [{
             ticks: {
                 beginAtZero:true
             }
         }]
     }
    }
    });

    this.serv.supplypayment = [];
    this.serv.supplyBrand= []

  }

2 个答案:

答案 0 :(得分:1)

尝试一下:

this.getSupply().subscribe (list => {
      this.supplypayments = list.map(item =>{
        return {
          $key: item.key,
          payment:item.payment,
          brandName:item.BrandName
        };
      });
}

您无需再次循环

在标记中,您可以访问以下值:

<ul>
  <li *ngFor="let supplyPayment of supplypayments">
    {{supplyPayment.$key}} - {{supplyPayment.payment.something}} - {{supplyPayment.brandName}}
  </li>
</ul>

答案 1 :(得分:0)

如果将supplypaymentsupplyBrand进行了单位化(因此未定义),则将发生这种情况。 getSupply之后的所有推入操作都不会引发任何错误,只是抛出错误(因为undefined.push is not a function)。但是在ngOnInit的末尾,您有这两行:

    this.serv.supplypayment = [];
    this.serv.supplyBrand= []

之后是适当的数组。

您应该

// initialize the arrays
supplypayment: number[] = []; // or is it string[], or any other type[]? 
supplyBrand: string[] = [];

//...

this.getSupply().subscribe(list => {
    const array = list.map(item => ({ ...item.payload.val() }); // you weren't using $key anyway

    this.supplypayment = array.map(item => item.payment);
    this.supplyBrand = array.map(item => item.BrandName);
}