Search code examples
angularangular11

console.log returns api data but ERROR TypeError: Cannot read properties of undefined reading 'name'


I dont understand i've already passed the parent data employeeNumber to user-seminar child component.

Here is my child component code

export class UserSeminarComponent implements OnInit {
  @Input() employeeNumber: number;

  seminar: IUserSeminar;
  // seminar: any;

  constructor(private apiService: ApiService, private spinner: SpinnerService) { }

  ngOnInit(): void {
    this.getUserSeminar();
  }

  private getUserSeminar(): void {
    // console.log(this.employeeNumber);
    this.apiService.getUserSeminar('users/seminar/', this.employeeNumber)
      .subscribe(
        data => {
          this.seminar = data;
          console.log(this.seminar);
        });
  }

}

Then try to display the data in html user-seminar.component.html

<p>{{ seminar.name }} test</p>

I have seminar interface

export interface IUserSeminar {
    id: number;
    user_id: number;
    dates: Array<string>;
    name: string;
    certificate_number: number;
}

data return successfully in console.log

[
   {
      "id":1,
      "user_id":1,
      "dates":"04-04-2022",
      "name":"test",
      "certificate_number":"123",
      "created_at":null,
      "updated_at":null,
      "user":{
         "id":1,
         "created_at":"2022-06-27T02:20:30.000000Z",
         "updated_at":"2022-06-27T03:18:59.000000Z",
         "first_name":"Super Admin",
         "last_name":"SIS",
         "middle_name":null,
         "suffix":null,
         "email":"[email protected]",
         "sex":"male",
         "birthdate":"2022-06-14",
         "employee_number":"22000001",
         "profile_picture":null,
         "address":null,
         "contact_number":"+1-202-555-0119",
         "date_of_employment":"",
         "alt_contact_number":"202-555-0119"
      }
   }
]

But im still getting error in my browser.


Solution

  • getting data - is async operation, at the begin u dont have any seminar, so u must add check or use operator like below

    <p>{{ seminar?.name }} test</p>

    also u receive array, but html display item property (did u use *ngFor="" ?)