Search code examples
angularangular2-changedetectionangular-changedetection

How to handle the refresh of a list of elements after deleting an element in the Backend


Let's say I have the component below. It displays a list of employees fetched from a backend service, and, as you can see, for every employee there is a delete button displayed, which, if clicked, triggers a backend call to delete the employee based on its ID. The delete backend service returns 200 if everything goes well, nothing more.

Now, to keep my employee list updated, I needed to call the fetch employees backend service again to get the updated list, which seems unfortunate to me since all it takes is to somehow trigger the asyn pipe to be executed again.

Could this be handled any better ?

@Component({
  selector: 'app-employee-home',
  template: '<div *ngFor="let employee of (employees$ | async) as employees">\n' +
    '  <ul>\n' +
    '    <li>{{employee.firstname}}</li>\n' +
    '    <li>{{employee.lastname}}</li>\n' +
    '  </ul>\n' +
    '  <button (click)="delete(employee.id)">Delete</button>\n' +
    '</div>',
  styleUrls: ['./employee-home.component.scss']
})
export class EmployeeHomeComponent{

  employees$!: Observable<any>;

  constructor(private httpClient: HttpClient,
              private router: Router) {
    this.employees$ = this.httpClient.get('http://localhost:8080/employees')
      .pipe(
        map(response => response.content )
      );
  }

  delete(id: any) {
    this.httpClient.delete(`http://localhost:8080/employees/${id}`)
      .subscribe(value => {
        this.employees$ = this.httpClient.get('http://localhost:8080/employees')
          .pipe(
            map(response => response.content )
          );
      });
  }
}

Solution

  • After getting the response of deletion just remove the element from dom. It is not required to call the employees api again.

    <div *ngFor="let employee of (employees$ | async) as employees" #ref>\n' +
        '  <ul>\n' +
        '    <li>{{employee.firstname}}</li>\n' +
        '    <li>{{employee.lastname}}</li>\n' +
        '  </ul>\n' +
        '  <button (click)="delete(employee.id, ref)">Delete</button>\n' +
        '</div>
    

    Now you have reference of element in the delete method and just remove it.

    delete(id: any, ref: HTMLElement) {
        this.httpClient.delete(`http://localhost:8080/employees/${id}`)
          .subscribe(() => {
            ref.remove();
          });
      }