Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

180
Visualizações
HttpClient: how to show data on DOM

This is an employee list from my mock db.json. I am trying to visualise it in the DOM. In the app.component.html if I write in the loop {{employee}}, it visualises a list of 2 items and each item is[object Object]. Otherwise if I write {{employee.name}} the error is: Property 'name' does not exist on type 'EmployeeService'.ngtsc(2339)

What am I missing? Any help will be appreciated.Thank you.

app.component.html:

{{title}}

<li *ngFor="let employee of employees">{{employee.name}}</li> //error with property name

app.component.ts

import { Component } from '@angular/core';
import { EmployeeService } from './service/employee.service';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  title = 'List of employees';

employees: EmployeeService[]=[];

constructor(private employeeService: EmployeeService) {}

ngOnInit(): void {
this.employeeService.getUsers().subscribe(emp => {
this.employees = emp;
  }) 
}
}

employee.service.ts

import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { Observable } from 'rxjs';

@Injectable({
  providedIn: 'root'
})
export class EmployeeService {

  constructor(private http: HttpClient) { }

  getUsers(): Observable<EmployeeService[]> {
    return this.http.get<EmployeeService[]>('http://localhost:3000/employees')
  }

}

db.json:

{
  "employees": [
    {
      "id": 1,
      "name": "Tim",
      "hired": true
    },
    {
      "id": 2,
      "name": "Jess",
      "hired": true
    }
  ]
}

about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

You could always see the data loaded to the template file using the json pipe operator,

Example <div>{{employees | json }}</div> , this will help you to understand the structure of data and access it correctly.

Solution to your problem:

The response from your getUsers() returns an object, that contains an array for employees. You were trying to access the data object.

Instead, you should retrieve the employees data from the object and loop through the employees data in your template file.

In your app.component.ts component:

import { Component } from '@angular/core';
import { EmployeeService } from './service/employee.service';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  title = 'List of employees';

employees: any[]=[]; // preferably a custom type/interface than 'any'

constructor(private employeeService: EmployeeService) {}

ngOnInit(): void {
this.employeeService.getUsers().subscribe(emp => {
this.employees = emp.employees;  // ------------------> Change
  }) 
}
}

Inside your app.component.html template:

<div *ngFor="let employee of employees">{{ employee.name }}</div>

In your employee.service.ts service

import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { Observable } from 'rxjs';

@Injectable({
  providedIn: 'root'
})
export class EmployeeService {

  constructor(private http: HttpClient) { }

  // Your custom interface/type should be the return type 
  getUsers(): Observable<any[]> {
    return this.http.get('http://localhost:3000/employees');
  }

}

Working app in Stackblitz

about 4 years ago · Juan Pablo Isaza Relatório

0

// check whether the employee list is not empty before rendering it in UI
<ul *ngIf="employees">
  <li *ngFor="let employee of employees">{{ employee.name }}</li>
</ul>


// To view complete JSON dump in web page follow below: Add this import statement to your app module

import { CommonModule } from '@angular/common';

then include it in imports 

@NgModule({
  ...,
  imports: [CommonModule, ...],
})

<!-- in your app.html: -->

<div *ngIf ="employees">
   {{ employees | json}}
</div>
about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda