Update Service

We start by defining two functions in the BMS service, deleteBookand deleteBookByID:

  • deleteBook is responsible for communicating with the API endpoint. We pass to it the book's ISBN as a parameter and the latter will be used as the endpoint's parameter to delete the book from the database.

  • deleteBookByID will delete the book from the local list that we have created so that we avoid fetching the list again and provide a better UX.

import { Injectable } from '@angular/core';
import { HttpClient } from "@angular/common/http";
import { Observable, BehaviorSubject, of } from 'rxjs';
import {Book} from '../models/book.model'

@Injectable({
  providedIn: 'root'
})
export class BmsService {
  // ...
  deleteBook(bookISBN: string): void {
     this.httpClient.delete<any>(`http://localhost:3000/api/user/deleteBook/${bookISBN}`).subscribe({
      next: (data: any) => {
        console.log(data);
        this.deleteBookByID(bookISBN);
      },
      error: (data: any) => console.log(data)

    })
  }
  
  private deleteBookByID(bookISBN: string) {
    const books: Book[] = this.listOfBooks.getValue();
    books.forEach((book, index) => {
      if(book.ISBN === bookISBN) {books.splice(index, 1);}
    })
    this.listOfBooks.next(books);
  }
  
}

In deleteBook we are using the HTTP Client to make a DELETE HTTP request to the backend server through the API endpoint. Note that we are not specifying the response's type (unlike what we did when fetching the list of books), that is why the function's call type parameter is set to any.

Once the request has been successfully made, we log the response to the console at line 14 (though this is an optional step, we are just doing so as a sanity check), then we invoke deleteBookByIDto delete the book from the local list.

Caution: Again, in an ideal setting you should properly handle errors by displaying them to your user so they would be aware if the system is not acting properly.

Coming to the deleteBookByIDfunction, we first create an auxiliary variable of type Book[] where we store the subject's current value and we operate on that variable. We iterate over the array to find the book with that specific ID. Once found, we delete it from the array using the method splice, that takes the starting index and the number of elements to be deleted (in the case it is just 1). Finally, we broadcast our new list to the subject.

Last updated