Search code examples
angulartypescriptrxjsangular-materialsubscription

Angular subscribe returns undefined object


So i have material dialog, in this dialog i have button

<button mat-icon-button 
 (click)="getChoosenEmployee(element)">
</button>

Element is type Employee:

export interface Employee {
    index: number;
    employeeId: string;
    firstName: string;
    lastName: string;
}

when i'm closing dialog i want to send this employee to parent component, this is what i'm doing:

  getChoosenEmployee(employee: Employee) {

    this.dialogRef.close(
      employee
    );
  }

in parent component i'm receiving by this function

dialogRef.afterClosed().subscribe(result => {
      console.log(this.choosenEmployee);
      this.choosenEmployees.push(this.choosenEmployee);
 });

pushing gives me error:

core.js:4197 ERROR TypeError: Cannot read property 'push' of undefined
    at SafeSubscriber._next (add-workday-form.component.ts:72)
    at SafeSubscriber.__tryOrUnsub (Subscriber.js:183)
    at SafeSubscriber.next (Subscriber.js:122)
    at Subscriber._next (Subscriber.js:72)
    at Subscriber.next (Subscriber.js:49)
    at Subject.next (Subject.js:39)
    at SafeSubscriber._next (dialog.js:381)
    at SafeSubscriber.__tryOrUnsub (Subscriber.js:183)
    at SafeSubscriber.next (Subscriber.js:122)
    at Subscriber._next (Subscriber.js:72)

Solution

  • Did you initialize your this.choosenEmployees array? That error is indicating that this.choosenEmployees is undefined, not the this.choosenEmployee object.