Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why angular subscribes multiple times?

Tags:

angular

rxjs

I have this structure:

  • product.service(for service)
  • product-search component(for setting the current checked object)
  • compare-product component(for subscribing the current checked object)

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...

like image 233
Marsha Avatar asked Dec 01 '22 14:12

Marsha


1 Answers

You need to unsubscribe to the observable when the component is destroyed. Each time you load the component, you have 1 subscription.

like image 140
Wandrille Avatar answered Dec 04 '22 03:12

Wandrille