[英]“Cannot read property 'push' of undefined ” Angular 9 component
I'm trying to create a nested array in my angular 9 component so I can call it in the template.我正在尝试在我的 angular 9 组件中创建一个嵌套数组,以便我可以在模板中调用它。 I'm not sure whether the problem is formatting or if there is something I'm doing fundamentally wrong.
我不确定问题是否出在格式上,或者我是否做错了什么。 I keep getting this error msg:
Cannot read property 'push' of undefined
我不断收到此错误消息:
Cannot read property 'push' of undefined
Here is my typescript:这是我的 typescript:
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
)
}
}
and here's my HTML:这是我的 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>
Thank you for your help!谢谢您的帮助!
I think what you are looking for is (either should work)我认为你正在寻找的是(要么应该工作)
export class AnalysisComponent implements OnInit {
//persuadables: Array<{'icon':string, 'desc':string, 'status':string}> = [];
//persuadables: {'icon':string, 'desc':string, 'status':string}[] = [];
}
I think that happened cause you wrote the type but you not defined array.我认为这是因为您编写了类型但未定义数组。
Try like this:试试这样:
export interface Persuadable {
icon: string;
desc: string;
status: string;
}
export class AnalysisComponent implements OnInit {
public persuadables: Array<Persuadable> = [];
}
Use interfaces and init your array.使用接口并初始化您的数组。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.