I would like to delete one employee at the time from the list of Employees.The Observable is set in the employee.service.ts and subscribed in the app.component.ts. There are problems to connect to the id of the employee with the method removeUser(id) in the app.component.html and the error is Property 'id' does not exist on type 'AppComponent'.ngtsc(2339).
- I would like to
console.logtheidwhen the relative delete button is clicked but I do not know how. - Something like
this.employees = this.employees.filter(employ => employ.id !== id)is needed to delete the employee, but I am not sure where to insert it.
employee.service.ts
import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { Observable } from 'rxjs';
import { EmployeeInterface } from '../types/employee.interface';
@Injectable({
providedIn: 'root'
})
export class EmployeeService {
constructor(private http: HttpClient) { }
getUsers(): Observable<EmployeeInterface[]> {
return this.http.get<EmployeeInterface[]>('http://localhost:3000/employees')
}
removeUser(id: string): Observable<{}> {
return this.http.delete(`http://localhost:3000/employeers/${id}`)
}
}
app.component.ts
import { Component } from '@angular/core';
import { EmployeeService } from './service/employee.service';
import { EmployeeInterface } from './types/employee.interface';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
title = 'List of employees';
employees: EmployeeInterface[]=[];
constructor(private employeeService: EmployeeService) {
}
ngOnInit(): void {
this.employeeService.getUsers().subscribe(emp =>
{
this.employees = emp;
console.log(this.employees)
})
}
removeUser(id: string): void {
this.employeeService.removeUser(`http://localhost:3000/users/${id}`).subscribe()
}
}
app.component.html
{{title}}
<li *ngFor="let employee of employees">{{employee.name}} <button (click)="removeUser(id)">Delete</button></li>
db.json (used with json server)
{
"employees": [
{
"id": 1,
"name": "Tim",
"hired": true
},
{
"id": 2,
"name": "Jess",
"hired": true
}
]
}