I'm trying to create a form to submit the details but when I subscribe the service, the subscription is done twice. First with null data and second with actual data.
Component.ts
addBook() {
this.errorMessage = null;
this.fireService.getBook(this.bookDetails.isbn).subscribe(data => {
console.log('subscribe called');
if (null != data) {
this.dbox.open(DialogBoxComponent, {
data: { title: 'Error', content: 'Book is already present in Library. Select Edit book to modify the details', button: false }
});
this.errorMessage = 'Book is already present in Library. Select Edit book to modify the details';
} else {
this.fireService.addBook(this.bookDetails);
this.dbox.open(DialogBoxComponent, {
data: { title: 'Success', content: 'Book has been Added to Database', button: false }
});
this.router.navigateByUrl('/add-book');
}
});
}
Service.ts
getBook(id) {
console.log('called firebase get book');
return this.db.doc(`/books/${id}`).valueChanges();
}
Below is the image from the console of chrome. This shows that the subscription is called twice but not the firebase service.
Chrome console logs: Image please click to view
chrome console logs
called firebase get book
subscribe called
subscribe called
Please help
It is because the observable returned by getBooks emits a new value when the Books collection changes. The first time there is no book with the same isbn so data is null. Then you add one book and so the same observable fires again, this time with the book you just added
If you only want to get data once, you can use take to only subscribe once.
this.fireService.getBook(this.bookDetails.isbn).take(1).subscribe(data => {
console.log('subscribe called');