Reputation: 1773
I'm using angular5 and angular firebase2. I have a simple question. I'm trying to make keyword comparing module now. Everything is fine, and actually, but observable is firing twice. I have no clue why it's firing exactly twice.
Here's my code.
/*add-store.component.ts*/
serverCheckKeyword(value) {
this.test = this.storeService.checkCategory();
this.test.subscribe(
data => {
if (data) {
// Here, firing twice
// some categories in Server
this.objToArr(data);
} else { // no categories in server
console.log('No data in server');
this.nothingData(value);
}
});
}
objToArr(data) {
//...
// I think I'm using this wrong. This part was the problem what I've figured out.
this.storeService.addCategory(this.sortKeyword[keywordIdx], size+1);
}
/*store.service.ts*/
addCategory(data, id) {
const path = `category/${data.name}`;
const item = {
id: id,
categoryName: data.name
};
this.db.object(path).update(item)
.catch(err => console.log(err));
}
// Load all of Categories
checkCategory() {
return this.db.list('category').valueChanges();
}
Upvotes: 0
Views: 1676
Reputation: 1773
Here's my answer to solve this issue.
I just this.test.unsubscribe()
after finishing logic.
serverCheckKeyword(value) {
this.test = this.storeService.checkCategory()
.subscribe(
data => {
// some categories in Server
if (data) {
// Here was firing twice
this.objToArr(data);
} else { // no categories in server
this.nothingData(value);
}
},
err => {
console.log(err);
});
}
...
this.storeService.addCategory(this.sortKeyword[keywordIdx], size + 1);
this.test.unsubscribe();
It works well! Thank you all :)
Upvotes: 0
Reputation:
This is probably because you went on another routed component, and you forgot to unsubscribe from the subscription.
Add a reference to your subscription
this['http_call'] = this.test.subscribe(...);
And delete it on destroy
ngOnDestroy() { this['http_call'].unsubscribe(); }
Otherwise, this can come from the fact that Firebase listens to databse events. This means that if you made a change to your base, your observer will be notified.
You can prevent that by "cancelling" the database listener with this
return this.db.list('category').valueChanges()
.pipe(take(1));
Upvotes: 2