【问题标题】:"Cannot read property 'push' of undefined " Angular 9 component“无法读取未定义的属性‘推送’”Angular 9 组件
【发布时间】:2020-10-10 18:07:18
【问题描述】:

我正在尝试在我的 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>

感谢您的帮助!

【问题讨论】:

    标签: arrays angular multidimensional-array angular-components


    【解决方案1】:

    我认为您正在寻找的是(应该可以)

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

    【讨论】:

    • 谢谢!这确实是问题所在。
    【解决方案2】:

    我认为这是因为您编写了类型但未定义数组。

    试试这样:

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

    使用接口并初始化您的数组。

    【讨论】:

      猜你喜欢
      • 2020-05-23
      • 2017-03-31
      • 2017-11-23
      • 1970-01-01
      • 2015-04-06
      • 1970-01-01
      • 2019-03-16
      • 1970-01-01
      • 2019-02-02
      相关资源
      最近更新 更多