简体   繁体   中英

Subscribe is called twice

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

like Chau Tran said, you can filter to get a valid response. If you haven't already, I'd add in a way to unsubscribe. In the code below this.alive is a field that is true, and turned false in the OnDestory life hook.

this.fireService.getBook(this.bookDetails.isbn)
.takeWhile(() => this.alive)
.filter(data => !!data)
.subscribe(...)

With in the function addBook you are calling the subscription. Each time you call the function addBook you are making a subscription call, Avoid using subscription in such functions. Make sure to subscribe only in onInit() , so that it checks whenever you make changes.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM