its me
its me

Reputation: 542

Cannot read property 'find' of undefined in angular?

I am getting this error when I use find html

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

when I click button dialog will open and I am passing listitem to dialog

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;

});

  }

}

Here I am getting this error:

TypeError: Cannot read property 'find' of undefined at DialogOverviewExampleDialog

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

Upvotes: 1

Views: 9606

Answers (2)

incognito nerd
incognito nerd

Reputation: 97

It means your this.Results object is undefined. Put a null check before that statement.

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

Upvotes: 0

Sajeetharan
Sajeetharan

Reputation: 222572

You need to place the check inside subscribe, otherwise Results will be undefined since you are making an async call

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;
        }
    });

Upvotes: 2

Related Questions