0

I'm trying to display an object attribute nested in another object. Each employee has a category. I manage to display employees attributes but not the category.name thanks for your help here is the code:

model:

export interface Category{
id : number;
name: string;
    }

import {Category} from "./Category";

export interface Employee {
  id: number;
  name: string;
  email: string;
  jobTitle: string;
  phone: string;
  imageUrl: string;
  employeeCode: string;
  active: boolean;
  category : Category;
}

service:

  public getEmployees(): Observable<Employee[]> {
    return this.http.get<Employee[]>(`${this.apiServerUrl}/employee/all`);
  }

app.ts

public getEmployees(): void {
    this.employeeService.getEmployees().subscribe(
      (response: Employee[]) => {
        this.employees = response;
        console.log(this.employees);
      },
      (error: HttpErrorResponse) => {
        alert(error.message);
      }
    );
  }}

html, error coming from {{employee?.category.name}}

<ul class="list-group list-group-flush">
          <li class="list-group-item"><i class="fa fa-envelope float-right"></i>{{employee?.email}}</li>
          <li class="list-group-item"><i class="fa fa-phone float-right"></i>Phone : {{employee?.phone}}</li>
          <li class="list-group-item"><i class="fa fa-briefcase float-right"></i>Active : {{employee?.active}}</li>
          <li class="list-group-item"><i class="fa fa-briefcase float-right"></i>Category : {{employee?.category.name}}</li>

JSON example of one object data that it received from backend:

 {"id":1,
"name":"ericparis",
"email":"[email protected]",
"jobTitle":"BA",
"phone":"06xxxxxxxx",
"imageUrl":"https://bootdey.com/img/Content/avatar/avatar1.png",
"active":true,
"category":{"id":1,"name":"cadre"}}
3
  • this should work i think. try {{employee?.category | json}} to have a look at the object in the html instead of accessing the name directly Commented Jun 13, 2021 at 5:43
  • Hi, can you specify what error you face in {{employee?.category.name}}. I tested it is able to display the value in HTML. You may create a Minimal Reproducible Example in StackBlitz. Commented Jun 13, 2021 at 6:15
  • are you getting any error while doing this.. Commented Jun 13, 2021 at 7:17

1 Answer 1

1

it sounds like one or several of the objects doesn't have a category. in this case this piece of code would fix that

{{employee?.category?.name}}
Sign up to request clarification or add additional context in comments.

1 Comment

error msg was : Object is possibly 'undefined', this solves the issue. Thanks for your help guys!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.