Home > Software design >  Angular delete button in HttpClient request with Json Server
Angular delete button in HttpClient request with Json Server

Time:11-28

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).

  1. I would like to console.log the id when the relative delete button is clicked but I do not know how.
  2. 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}`)
  }

} 
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

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()
}

}
<iframe name="sif2" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

app.component.html

{{title}}

<li *ngFor="let employee of employees">{{employee.name}} <button (click)="removeUser(id)">Delete</button></li>
<iframe name="sif3" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

db.json (used with json server)

{
  "employees": [
    {
      "id": 1,
      "name": "Tim",
      "hired": true
    },
    {
      "id": 2,
      "name": "Jess",
      "hired": true
    }
  ]
}
<iframe name="sif4" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

CodePudding user response:

It's because on your html file you are calling a function using a variable named 'id', that is supposed to exist in your component file, that's why you are getting that error.

Instead, you need the id of the employee that you are getting at that time from the ngFor, so you need this:

<li *ngFor="let employee of employees">{{employee.name}} <button (click)="removeUser(employee.id)">Delete</button></li>

Just like you did with the name of the employee.

CodePudding user response:

Ok, there are some problems in your code.

  1. In your HTML template, you are not passing the employee ID in the button click output. Because of this you are getting the mentioned error. Your HTML code must be like:
<button (click)="removeUser(employee.id)">Delete</button>
  1. In AppComponent.removeUser, you are passing the complete URL to the service method. You only have to pass the id, like below:
removeUser(id: string): void {
   this.employeeService.removeUser(id).subscribe()
}
  1. You must do the mentioned filter only if the delete request have been successful. For achieve this, your AppComponent.removeUser will be like this:
removeUser(id: string): void {
   this.employeeService.removeUser(id)
      .subscribe(() => {
         this.employees = this.employees.filter(employ => employ.id !== id)
      })
}
  1. To console.log your employee ID, modify again the method:
removeUser(id: string): void {
   console.log(`ID of the employee to be removed: ${id}`)
   this.employeeService.removeUser(id)
      .subscribe(() => {
         this.employees = this.employees.filter(employ => employ.id !== id)
      })
}
  1. Your AppComponent.removeUser can be improved to show a error message to the user if the request fail and a success message too:
removeUser(id: string): void {
   console.log(`ID of the employee to be removed: ${id}`)
   this.employeeService.removeUser(id)
      .subscribe({
         next: () => {
            this.employees = this.employees.filter(employ => employ.id !== id)
            console.log(`The employee with ID = ${id} have been removed.`)
            // TODO - Show the success message for the user.
         },
         error: () => {
            console.log(`An error occurred when trying to remove the employee with ID = ${id}.`)
            // TODO - Show the error message for the user.
         }
       })
}
  • Related