Search code examples
angularangular-httpclient

Get nested object with httpClient in Angular


I am trying to get the nested object to display in the template with a get request. The issue is it display the main properties of my object, though, the nested object.

export class User {
  userId: number;
  userName: string;
  password: string;
  firstName: string;
  lastName: string;
  role: number;
  inforamation: Information;
}

This is my model which can show user properties but not information.

getAllUsers(){
    const header = new HttpHeaders({
      'Content-Type':  'application/json'
    });
    return this.usersapiservice.getData(this.REST_API_SERVER, {headers : header});
  }



ngOnInit(){
this.getAllUsers().subscribe((data: User[]) => {
      this.users = data;
    });
}

In my html

{{users.firstname}} // work

{{users.information.adress}} // Does not work

Solution

  • I see a couple of issues. In the User class, you misspelled one of the properties as inforamation, but in the template, the property is spelled correctly as information.

    If you have an array of Users that you want to render, you can use Angular's *ngFor to iterate through them, as shown below:

    <div *ngFor="let user of users">
      {{user.firstName}}
      {{user.information.address}}
    </div>