I have this structure:
I want to subscribe to an object in the service whenever the compare-product is loaded. It seems fine at first. But, when I hit the back button to the product-search, then load the compare-product again, it subscribes twice. When I go back and load again, it is called three times. Back, load again, called four times, and so on.
these are the codes:
service:
//product.service
.......
private checkedSrc = new BehaviorSubject([]);
currentChecked = this.checkedSrc.asObservable();
.......
setChecked(checked: string[]){
this.checkedSrc.next(checked);
}
resetChecked(){
this.checkedSrc.next([]);
}
.......
product-search component:
......
compare(){
this.products_valid = true;
this.productSvc.setChecked(this.checked);
this.router.navigate(['compare']);
}
......
compare-product component:
...
products: string[];
isLoading: boolean = true;
constructor(
private productSvc: ProductsService
) { }
ngOnInit() {
this.productSvc.currentChecked.subscribe(p => {this.products = p; console.log(this.products)})
}
I have tried it without navigating to the compare component. When I first call the compare function it subscribes once, call the compare again it subscribes twice, call again it subscribes three times, and so on.
......
compare(){
this.products_valid = true;
this.productSvc.setChecked(this.checked);
this.productSvc.currentChecked.subscribe(p =>{console.log(p);})
}
......
Button that calls it:
<div class="row">
<div class="col-md-6">
<button class="btn btn-primary" style="margin-top: 20px;" (click)="compare()">Compare</button>
</div>
</div>
I also have tried to reset the object with resetChecked() everytime the compare method called, but still the same...
You need to unsubscribe to the observable when the component is destroyed. Each time you load the component, you have 1 subscription.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With