0

我有一个组件在这里声明数字数组 public numbers :number[] =[];并在服务响应中给出数字数组的值并获得 10 并且在 ngInit 块之后它显示为未定义

app.component.ts

    export class AppComponent implements OnInit {  

      public numbers :number[] =[];  // here declare the variable
      public numberss :Iproduct[]

       ngOnInit(){ 
    // here call the service 

     this._productService.getproducts().subscribe((response) => {this.numberss = response;

    this.errornumber = 10;  // here ressign the value

    }
 }),(err)=> {this.errorMsg =<any>err};

       } // end of ngInit

// here is the 3rd party chart js  pass the this.errornumber gets undefined

    public doughnutChartOptions: any = {
      elements: {
        center: {
          text:this.errornumber +"% <br>products" ,
        }
      }
    };

    } // end of component

这里未定义原因:text:this.errornumber

4

1 回答 1

1

因为在定义 donutChartOptions 时 this.errornumber 还不存在,所以它是未定义的。在产品由服务返回后,它被创建和初始化。因此,您应该移动创建 donutChartOptions 字段以进行订阅。

Example

https://plnkr.co/edit/CSXxSoWhxppw9ran4AcM?p=preview

于 2017-11-13T18:53:17.803 回答