Update Service

First we have to add two new functions, namely: addBook and addNewBook.

  • addBook is responsible for making the backend API call to add a new book. In the request body, we pass the book object that has been specified in the parameters.

  • addNewBook is a private method as only the service should be able to update the list of books and no other component. It is responsible for keeping the list of books up to date.

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 {
  // ...
  addBook(book: Book): void {
     this.httpClient.post<any>("http://localhost:3000/api/user/addBook", book)
       .subscribe({
         next: (data: any) => {
          this.addNewBook(book);
          console.log(data);
         },
         error: (data: any) => console.warn(data)
       })
  }

  private addNewBook(book: Book) {
    const books: Book[] = this.listOfBooks.getValue();
    books.push(book);
    this.listOfBooks.next(books);
  }
}

Caution: you should only add the functions addBook and addNewBook rather than replace the entire content of bms.service.ts with the code above. For the sake of brevity, we omit all unnecessary pieces of code. Whenever a portion of code is omitted, it is replaced by the following indicator:// ...

As mentioned earlier, addBook makes a POST HTTP request to the backend server. It sends in the request body the book that it received as an argument. Since HTTP calls are asynchronous, we have to wait for the response of the backend by subscribing.

If the request does not go through for whatever reason, we will get an error and in that case we simply print it to the console.

Caution: Keep in mind that this is done for demonstration purposes. In reality, all errors should be handled properly and the user should be made aware that the system is misbehaving.

On the other hand, if the request succeeds, we can safely update our list of books that we defined in the service by calling addNewBook.

Last updated