"Cannot read property 'push' of undefined " Angular 9 分量

"Cannot read property 'push' of undefined " Angular 9 component

我正在尝试在我的 angular 9 组件中创建一个嵌套数组,以便我可以在模板中调用它。我不确定问题是格式问题还是我做的根本错误。我不断收到此错误消息:Cannot read property 'push' of undefined

这是我的打字稿:

import { Component, OnInit } from '@angular/core';

@Component({
  selector: 'ngx-analysis',
  templateUrl: './analysis.component.html',
  styleUrls: ['./analysis.component.scss']
})
export class AnalysisComponent implements OnInit {

    persuadables: [{'icon':string, 'desc':string, 'status':string}];

    constructor() { }

    ngOnInit() {
        this.persuadablePush();
    }

significance(score, name, arr){

        if (score == 1.0){
            arr.push({'icon':'checkmark-done-circle', 'desc': 'Very ' + name.toLowerCase(), 'status':'success'}) ;
        }
        else if (score == 0.5){
            arr.push({'icon':'checkmark-circle', 'desc':name, 'status':'info'}) ;
 
        }
        else if (score == 0.0){
            arr.push({'icon':'close-circle', 'desc': 'Not ' + name.toLowerCase(), 'status':'danger'}) ;

        }
    }
persuadablePush(){

        for( let i=5; i<10; i++ ){

            this.significance(
                this.insights['consumption_preferences'][0]['consumption_preferences'][i]['score'],// =number
                this.insights['consumption_preferences'][0]['consumption_preferences'][i]['name'],// =string
                this.persuadables
            )
        }
    }

这是我的 HTML:

<nb-card size="small">
      <nb-card-header>Persuadables</nb-card-header>
      <nb-card-body>
        <nb-list *ngFor='let obj of persuadables'>
            <nb-icon icon='obj.icon' status='obj.status'></nb-icon>
            {{obj.desc}}
        </nb-list>
      </nb-card-body>
    </nb-card>

感谢您的帮助!

我认为您正在寻找的是(两者都应该有效)

export class AnalysisComponent implements OnInit {
    //persuadables: Array<{'icon':string, 'desc':string, 'status':string}> = [];
    //persuadables: {'icon':string, 'desc':string, 'status':string}[] = [];
}

我认为发生这种情况是因为您编写了类型但未定义数组。

这样试试:

export interface Persuadable {
  icon: string;
  desc: string;
  status: string;
}
export class AnalysisComponent implements OnInit {
    public persuadables: Array<Persuadable> = [];
}

使用接口并初始化数组。