Home > other >  how to unsubscribe nested observable | Angular
how to unsubscribe nested observable | Angular

Time:09-25

Depending on the URL param, i am subscribing to an observable (_getData).

  ngOnInit(): void {
    this._subscription.add(
      this.route.queryParamMap.subscribe((params) => { this._getData(params.get('name')).subscribe() })
    );
  }

  ngOnDestroy(): void {
    this._subscription.unsubscribe();
  }

Now every time the param changes, I am subscribing to a new observable (_getData).. So how do i unsubscribe the previous observable?

CodePudding user response:

You can use mergeMap to flatten the inner observable which is the this._getData()

In the code below, I didn't subscribe to your second observable and instead used mergeMap. I did this so that there is only 1 child subscription and will be unsubscribed by the parent this._subscription when you unsubscribe from it.

this._subscription.add(
  this.route.queryParamMap.pipe(
    mergeMap((params) => {
      return this._getData(params.get('name'))
    })
  ).subscribe()
);

CodePudding user response:

You can use switchMap to manage your subscriptions for you. In this case, every time there are new params, the old this._getData is unsubscribed and a new this._getData is subscribed for you.

ngOnInit(): void {
  this.route.queryParamMap.pipe(
    switchMap(params => this._getData(params.get('name')))
  ).subscribe();
}
  • Related