Esta es una lista de empleados de mi simulacro db.json . Estoy tratando de visualizarlo en el DOM . En app.component.html si escribo en el bucle {{employee}} , visualiza una lista de 2 elementos y cada elemento es [object Object] . De lo contrario, si escribo {{employee.name}} , el error es: Property 'name' does not exist on type 'EmployeeService'.ngtsc(2339)
¿Qué me estoy perdiendo? Cualquier ayuda será apreciada. Gracias.
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 } ] }Siempre puede ver los datos cargados en el archivo de plantilla usando el operador de canalización json,
Ejemplo <div>{{employees | json }}</div> , esto lo ayudará a comprender la estructura de los datos y acceder a ellos correctamente.
Solución a su problema:
La respuesta de getUsers() devuelve un objeto que contiene una matriz para los empleados. Estaba intentando acceder al objeto de datos.
En su lugar, debe recuperar los datos de los employees del objeto y recorrer los datos de los employees en su archivo de plantilla.
En su componente 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: any[]=[]; // preferably a custom type/interface than 'any' constructor(private employeeService: EmployeeService) {} ngOnInit(): void { this.employeeService.getUsers().subscribe(emp => { this.employees = emp.employees; // ------------------> Change }) } } Dentro de su plantilla app.component.html :
<div *ngFor="let employee of employees">{{ employee.name }}</div> En su servicio 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) { } // Your custom interface/type should be the return type getUsers(): Observable<any[]> { return this.http.get('http://localhost:3000/employees'); } }Aplicación de trabajo en Stackblitz
// 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>