无法读取角度中未定义的属性“find”?

时间:2018-02-01 06:08:55

标签: javascript angular angular-material

当我使用find时,我收到此错误 HTML

<button  (click)="saveDialog(listitem)"></button>

当我单击按钮时,对话框将打开,我将listitem传递给对话框

DialogOverviewExampleDialog

export class DialogOverviewExampleDialog {

  constructor(
    public dialogRef: MatDialogRef<DialogOverviewExampleDialog>,
    @Inject(MAT_DIALOG_DATA) public data: any,
    private formBuilder: FormBuilder,private http: HttpClient) {

  this.selectedElementSymbols = this.Results.find(e => e.name === this.data.listitem.name).symbols;

});

  }

}

我收到此错误:

  

TypeError:无法在DialogOverviewExampleDialog中读取未定义的属性'find'

this.selectedElementSymbols = this.Results.find(e => e.name === this.data.listitem.name).symbols;

2 个答案:

答案 0 :(得分:2)

您需要将支票放在 subscribe 内,否则因为您正在进行异步通话,结果将是未定义的

this.http.get('https://myjson.com/qbot1')
    .subscribe((res:any) => {
        this.Results = res;
        if (data.listitem) {
            this.selectedElementSymbols = this.Results.find(e => e.name === this.data.listitem.name).symbols;
        }
    });

答案 1 :(得分:0)

这意味着您的this.Results对象未定义。在该语句之前放置一个空检查。

if(this.Results)
this.selectedElementSymbols = this.Results.find(e => e.name === this.data.listitem.name).symbols;