I am able to fetch all books but Delete is not working. Dont know why? deleteByBookId method in service class is not working. Is it because I am not using json server? My service class is below
import { Injectable } from "@angular/core";
import { IBook } from './book';
import { BookList } from './app.booklist';
import { Observable } from 'rxjs';
import { HttpClient, HttpHeaders } from '@angular/common/http';
import { element } from 'protractor';
@Injectable()
export class BookService {
httpOptions = {
headers: new HttpHeaders({
'Content-Type': 'application/json'
})
}
bookUrl: string = '../assets/books.json';
boo: IBook = new IBook();
public static bookList: IBook[] = [];//My Array
constructor(private httpClient: HttpClient) {
this.httpClient.get<IBook[]>(this.bookUrl).subscribe(book => {
BookService.bookList = book; //storing in array
});
}
getBookListByHttp(): Observable<IBook[]> {
return this.httpClient.get<IBook[]>(this.bookUrl);
}
deleteBookById(id: number): void { //this method is not working
this.httpClient.delete<IBook>(this.bookUrl + '/' + id, this.httpOptions);
}
}
My BookList class
import { BookService } from './bookservice';
import { IBook } from './book';
import { OnInit, Component } from '@angular/core';
@Component({
templateUrl: './app.bookcomponent.html',
providers: [BookService]
})
export class BookList implements OnInit {
status: boolean = true;
books: IBook[];
constructor(private bookservice: BookService) {
}
ngOnInit() {
this.bookservice.getBookListByHttp()
.subscribe(book => this.books = book);
}
deleteBookById(bookId: number): void {
this.bookservice.deleteBookById(bookId);
}
}
Html file associated with BookList class
<table border="2">
<tr>
<th>ID</th>
<th>NAME</th>
<th>Cost</th>
<th>Author</th>
<th>Delete</th>
<th>Edit</th>
</tr>
<tr *ngFor="let book of books">
<td><input type="number" value="book.bookId" [(ngModel)]="book.bookId" [readonly]="status"></td>
<td><input type="text" value="book.bookName" [(ngModel)]="book.bookName" [readonly]="status"></td>
<td><input type="number" value="book.bookCost" [(ngModel)]="book.bookCost" [readonly]="status"></td>
<td><input type="text" value="book.bookAuthor" [(ngModel)]="book.bookAuthor" [readonly]="status"></td>
<td><button (click)="deleteBookById(book.bookId)">Delete</button></td>
<td><button (click)="status = !status">Edit/Save</button></td>
</tr>
</table>
My Json file and its location is Project>src>assets>books.json
[
{
"bookId": 101,
"bookName": "Angular",
"bookCost": 6000,
"bookAuthor": "Ritu Raj"
},
{
"bookId": 102,
"bookName": "Angular 2",
"bookCost": 6600,
"bookAuthor": "Ritu Raj"
}
]