Accessing properties within nested objects in a class

In my Angular 7 application, I have two object classes filled with data - employee and company (data retrieved through a web API from a database).

The Employee class has fields - emp_id, name, surname, and a company object.
The Company class has - c_id, company_name, phone.
I am able to display the emp_id, name, and surname of an employee in a table using "emp_id", "name", and "surname" respectively. However, when trying to display the employee's company, it shows "[object Object]" instead of the desired company_name.

When viewing the data from the web API in a program like Postman, the company object is correctly displayed inside the employee object.

I have attempted various combinations to access the company name - company.company_name, company{company_name}, company(company_name), but none of these seem to work.

Below are my Angular classes:

export interface Employee
{
  emp_id: number;
  name: string;
  surname: string;
  company: Company;
}
export interface Company
{
  c_id: number;
  company_name: string;
  phone: string;
}

The objects are populated using http.get and saved in arrays:

public apartments: any[];
public houses: any[];

getEmployees(): Observable<Employee[]>
{
  return this.http.get<Employee[]>('http://localhost:60962/api/employees');
}

getCompanies(): Observable<Company[]>
{
  return this.http.get<Company[]>('http://localhost:60962/api/companies');
}

Subscribed on initialization:

ngOnInit()
{
 this.getEmployees()
     .subscribe(data => this.apartments = data);

 this.getCompanies()
     .subscribe(data => this.houses = data);
}  

Answer №1

One important rule for interfaces is to always begin with a capital letter:

export interface Employee {
  emp_id: number;
  name: string;
  surname: string;
  company: Company;
}

export interface Company {
  c_id: number;
  company_name: string;
  phone: string;
}

To create an object, follow this structure:

public test: Employee = {
    emp_id: 0,
    name: "test",
    surname: "test2",
    company: {
      c_id: 12,
      company_name: "cmp name",
      phone: "+665589898"
    }
  }

In your HTML code, you can access the properties like this:

{{test.name}}
{{test.company.phone}}

Make sure the interface property names match exactly when declaring objects, as inconsistency could cause errors.

See a live example here: https://stackblitz.com/edit/angular-joap5a?file=src%2Fapp%2Fapp.component.html

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

There are currently no examples demonstrating how to populate row headers and dynamic columns in the Material table

Currently, I am facing a situation where I need to have rows as headers and dynamic values in columns for a material table. Below is an example: Department Deparment1 Name Jack Vimal Location Chenn ...

When utilizing the dispatch function with UseReducer, an unexpected error is triggered: Anticipated 0 arguments were provided,

Having trouble finding a relevant answer, the only one I came across was related to Redux directly. So here's my question that might be obvious to some of you. In my code, everything appears to be correct but I'm facing an error that says: Expect ...

Encountering the "potential null object" TypeScript issue when utilizing template ref data in Vue

Currently, I am trying to make modifications to the CSS rules of an <h1> element with a reference ref="header". However, I have encountered a TypeScript error that is preventing me from doing so. const header = ref<HTMLElement | null> ...

Tips for maintaining the original form state when adjusting and then undoing changes in Angular2

Whenever I open a form from my web app to edit a page, my goal is for the page to remain in its original state if no changes are made. Unfortunately, even without changing any values and submitting the form, the page's state is still altered. I att ...

The functionality of the disabled and checked options on the radio button seems to be malfunction

Within an Angular HTML document, I have a set of radio buttons that share common names. I am attempting to update their disabled and checked properties from a .ts file, but the changes are not taking effect. Here is the code snippet: let elements = docume ...

Issue encountered during ng build using Angular 6 flag configurations

Upon attempting to build my app with specific flags, I encountered an error. When using only ng build, the process is successful. However, when adding flags such as: ng build -aot -vc -cc -dop --buildOptimize The following errors were displayed: An is ...

The Ajax request is malfunctioning when passing local variables as parameters

In my code behind, I have defined a webMethod like this: [System.Web.Services.WebMethod] public static string testCall(int qid, String answerContent) { log.Debug("this is call from jquery" + qid.ToString() + answerContent); ...

The Blazor Hybrid .apk app successfully integrates with gRPC while in Debug mode, but encounters issues when switched to Release mode

After developing my Blazor Hybrid application, I encountered an issue with the login screen functionality. When a user enters their information and clicks the button, the data is supposed to be sent to the server via a gRPC service. Surprisingly, while ru ...

Creating a Robust Next.js Build with Tailor-Made Server (Nest.js)

I'm in need of assistance with compiling/building my project using Next.js while utilizing a custom server. Currently, I have integrated Nest.js (a TypeScript Node.js Framework) as the backend and nested Next.js within it. The integration seems to be ...

encountering an issue during the installation of a node package

Encountering this error while trying to install npm i npm ERR! While resolving: <a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="9bfaf5fceef7fae9b6f2f6fafcfeb6fefff2eff4e9dbabb5abb5aa">[email protected]</a> npm ERR! ...

Could registering .NET types for COM be achieved using this method?

I have a .NET assembly that I've registered for COM using regasm.exe. This tlb is then utilized by users to write VBA code in Excel. After running regasm /regfile, I noticed that all registry entries are being placed under 'HKEY_CLASSES_ROOT&bso ...

Tips for Decreasing Query Time with MatTable and MatTableDataSource

When working with my firestore database, I am trying to query documents and display them while also calculating the total value of a specific column (promiAmount). I have successfully displayed the values in a mat table, but I'm struggling to calcula ...

Guide to converting a string into an undefined type

I've been working on parsing a csv file: let lines = csvData.split(/\r\n|\n/); let headers = lines[0].split(','); for (let i = 1; i < lines.length; i++) { let values = lines[i].split(','); ...

What is the reason behind Java's limitation in supporting generics without resorting to raw types and type erasure, unlike .NET?

In the world of programming languages, Java has its own unique approach to dealing with generics compared to .NET. The reason behind the existence of raw types and type erasure in Java can be attributed to the introduction of generics and the need for main ...

Incorporating an additional ion-item alongside the existing one instead of substituting it

I am retrieving a list of questions from an API with pagination. I have a button that triggers a function to load the next page of questions. Instead of replacing the previous page, I want to append the new questions below the existing ones. Here is my cur ...

How to retrieve data from a nested object in Angular templates

I am working with a "post" object that has an "author" property, linking each post to the author who created it. The "author" property is a nested "user" object with a "name" property. My goal is to access the "name" of the user associated with a specifi ...

Error with React, key must be unique. What's the issue?

What is causing the issue with unique keys? To resolve the problem, ensure that each list item has a unique key. For example, if we have x_values = {'male':[1,2,3], 'female':[2,3,4]} the keys should be : 'mean-male', ' ...

Enhancing NG Style in Angular 6 using a custom function

Today, my curiosity lies in the NG Style with Angular 6. Specifically, I am seeking guidance on how to dynamically update [ngStyle] when utilizing a function to determine the value. To better illustrate my query, let me present a simplified scenario: I ha ...

How to attach input to function invocation in Angular 2

Can we connect the @Input() property of a child component to a parent component's function call like this: <navigation [hasNextCategory]="hasNextCategory()" [hasPreviousCategory]="hasPreviousCategory()" (nextClicked)="next ...

What is the method for determining the type of a generic object?

In the scenario where I need to accept a generic list of elements as a method parameter and execute different actions based on the type of objects within the list, I can use the following approach: Private Sub DoStuff(Of T)(ByRef list As List(Of T) I ...