LogoLogo
  • Introduction
  • Backend
    • Creating a MongoDB Database
    • Environment Variables
    • Configuring the Mailing Service
    • Seeding the Database
    • Starting the Backend
  • Frontend
    • Starting the Frontend
  • Book Module Tutorial
    • Introduction
    • Backend
      • Create Model
      • Create Service
      • Create Route
      • Test using Postman
    • Frontend
      • Introduction
      • File Structure
      • Defining Concepts
      • Display App in Dashboard
      • Create Module
      • Create Book List Component
      • Create Main Component
      • Create Service
      • Display Book List
      • Add a Book
        • Update Service
        • Create Component
        • Final Code Review
      • Delete a Book
        • Update Service
        • Update Component
        • Final Code Review
      • Conclusion
  • Resources
  • Beginner
  • Advanced
  • Recommended Extensions for Visual Studio Code
  • Troubleshooting
    • Troubleshooting
Powered by GitBook
On this page

Was this helpful?

Export as PDF
  1. Book Module Tutorial
  2. Frontend
  3. Delete a Book

Final Code Review

By now, ListBooksComponent files and BMS service should be look like this,

import { Component, OnInit, OnDestroy} from '@angular/core';
import {BmsService} from "@app/shared/services"
import { Book } from "@app/shared/models";
import { BehaviorSubject, Observable } from 'rxjs';
import { Router } from '@angular/router';


@Component({
  selector: 'app-list-books',
  templateUrl: './list-books.component.html',
  styleUrls: ['./list-books.component.css']
})
export class ListBooksComponent implements OnInit,OnDestroy{

  listOfBooks: BehaviorSubject<Book[]> = new BehaviorSubject<Book[]>([]);
  // Second
  bookRemoved: BehaviorSubject<boolean> = new BehaviorSubject<boolean>(false);

  constructor(public bmsService: BmsService, private router: Router) { }

  ngOnInit() {
   this.bmsService.getList().subscribe(books => this.listOfBooks.next(books));
  }

  ngOnDestroy() {
  }

  deleteBook(bookISBN: string) {
    this.bmsService.deleteBook(bookISBN);
    this.bookRemoved.next(true);
    
  }

  goToAdd() {
    this.router.navigate(["/apps/bms/add"])
  }

}
<ng-container *ngIf="this.bookRemoved | async">
  <div class="alert alert-success alert-dismissible fade show" role="alert">
    The Book Has Been Successfully Removed.
    <button type="button" class="close" data-dismiss="alert" aria-label="Close">
      <span aria-hidden="true">&times;</span>
    </button>
  </div>
</ng-container>

<div class="table-responsive">
  <table class="table">
    <thead class="thead-dark">
      <tr>
        <th scope="col">#</th>
        <th scope="col">Title</th>
        <th scope="col">Author</th>
        <th scope="col">ISBN</th>
        <th scope="col">Action</th>
      </tr>
    </thead>
    <tbody>
      <ng-container *ngFor="let book of listOfBooks | async; let i = index;">
        <tr>
          <th scope="row">{{i}}</th>
          <td>{{book.Title}}</td>
          <td>{{book.Author}}</td>
          <td>{{book.ISBN}}</td>
          <td><button type="button" class="btn btn-danger" 
          (click)="deleteBook(book.ISBN)">Delete</button>
          </td>
        </tr>
      </ng-container>
    </tbody>
  </table>
  <div class="btn-group" role="group" aria-label="Basic example">
    <button type="button" class="btn btn-success" 
    (click)="goToAdd()">Add Book</button>
  </div>

</div>
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 {

  constructor(private httpClient: HttpClient) { }

  listOfBooks: BehaviorSubject<Book[]> = new BehaviorSubject<Book[]>([]);

  getBooks(): void {
   this.httpClient.get<Book[]>("http://localhost:3000/api/user/getBooks").subscribe({
    next: (data: Book[]) => this.listOfBooks.next(data),
    error: (data: any) => console.log(data)

  })
  }

  getList(): Observable<Book[]> {
    if(of(this.listOfBooks)) {
      this.getBooks();
    }
    return this.listOfBooks.asObservable();
  }

  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)

    })
  }

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

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


PreviousUpdate ComponentNextConclusion

Last updated 4 years ago

Was this helpful?