Having some trouble displaying registered employees in my Angular app. It seems that the values are not appearing, only their array items are being created. I checked with a console.log and it looks like the variables are undefined. Any assistance would be appreciated.
employee.component.html
<div class="row animated fadeIn">
<div class="col-12">
<div class="card">
<div class="card-body">
<h3 class="card-title"> Registered Employees </h3>
<table class="table table-hover" >
<thead>
<tr>
<th>Name</th>
<th>Code</th>
<th>Position</th>
<th>Office</th>
<th></th>
</tr>
</thead>
<tbody>
<tr *ngFor="let employee of employees">
<td>{{employee.name}}</td>
<td>{{employee.code}}</td>
<td>{{employee.position}}</td>
<td>{{employee.office}}</td>
<td>
<button class="btn btn-primary"> <i class="fa fa-save"></i></button>
<button class="btn btn-danger"> <i class="fa fa-trash-o"></i></button>
</td>
</tr>
</tbody>
</table>
</div>
</div>
</div>
</div>
employee.component.ts
import { Component, OnInit } from '@angular/core';
import { Employee } from '../models/employee.model';
import { EmployeeService } from '../services/employee.service';
@Component({
selector: 'app-employee',
templateUrl: './employee.component.html',
styleUrls: ['./employee.component.css']
})
export class EmployeeComponent implements OnInit {
employees: any[] = [];
constructor(public employeeServ: EmployeeService) { }
ngOnInit() {
this.retrieveEmployees();
console.log(this.employees.length);
}
retrieveEmployees() {
this.employeeServ.getEmployees()
.subscribe( (resp: any) => {
console.log(resp[0].name);
for (let index = 0; index < resp.length; index++) {
this.employees[index] = resp[index];
console.log(this.employees[index]);
}
// JSON.stringify(this.employees);
console.log(this.employees[0].name);
});
}
}
employee.service.ts
import { Injectable } from '@angular/core';
import { Employee } from '../models/employee.model';
import { HttpClient } from '@angular/common/http';
import { Observable, throwError } from 'rxjs';
import { map, catchError } from 'rxjs/operators';
import swal from 'sweetalert';
@Injectable({
providedIn: 'root'
})
export class EmployeeService {
constructor(public http: HttpClient) { }
saveEmployee(employee: Employee): Observable<any> {
return this.http.post('http://localhost:62200/api/Employee', employee)
.pipe(
map( (resp: any) => {
swal('Employee created', employee.name, 'success');
return employee;
}),
catchError((e: any) => throwError(e))
);
}
getEmployees() {
return this.http.get('http://localhost:62200/api/Employee');
}
deleteEmployee(id: number): Observable <any> {
return this.http.delete('http://localhost:62200/api/Employee/' + id)
.pipe(
map( (resp: any) => {
swal('Employee deleted', 'Deleted', 'warning');
return resp;
}),
catchError((e: any) => throwError(e))
);
}
}
When attempting to display the employees, the items are created but the name, code, position, and office details don't appear.