Fabiana Faria
Fabiana Faria

Reputation: 23

how to filter activatedRoute.queryParams and subscribe to different observables according to the filter

The problem: My app might receive querystring params and depending on which param is in the querystring different actions need to be done:

1) Here I look for advertiser in querystring, if it is there I need to subscribe to a service that will validate the advertiser:

this.activatedRoute.queryParams
  .filter(data => data.hasOwnProperty('advertiser'))
  .mergeMap(v => {
    advertiserId = v.advertiser;
    return this.myService.advertiserCheck(v.advertiser);
  })
  .subscribe(data => {
    if (true === data.valid) {
      // some processing takes place
    }
  });

2) Here I look for orderKey param:

this.activatedRoute.queryParams
  .filter(data => data.hasOwnProperty('orderKey'))
  .mergeMap(() => this.activatedRoute.firstChild.firstChild.url)
  .subscribe(segments => {
    // some processing takes place with the url segments
  });

As you can see I am subscribing to ActivatedRoute.queryParams twice. Is there a way I can combine the 2? I tried the following:

this.activatedRoute.queryParams
  .filter(data => data.hasOwnProperty('advertiser') || data.hasOwnProperty('orderKey'))
  .mergeMap(v => {
    if (v.hasOwnProperty('advertiser')) {
      advertiserId = v.advertiser;
      return this.myService.advertiserCheck(v.advertiser);
    } else {
      return this.activatedRoute.firstChild.firstChild.url;
    }
  })
  .subscribe(data => {
    console.log('which one am I handling?');
});

These parameters are not going to be in the querystring at the same time but in the subscribe I do not know which one am I handling. I suppose I can create a variable and then check that inside the subscribe but it doesn't look very elegant. Is there a better way? Should I leave as it is so it is less confusing?

Upvotes: 2

Views: 1255

Answers (1)

LLai
LLai

Reputation: 13416

I would leave them as 2 independent sequences since they have different end results. But I would also have them share the same underlying observable sequence with the shareReplayoperator.

ngOnInit(){
    this.obs$ = this.activatedRoute.queryParams
        .shareReplay();

    // sequence 1
    this.obs$
        .filter(data => data.hasOwnProperty('advertiser'))
        .mergeMap(v => {
            advertiserId = v.advertiser;
            return this.myService.advertiserCheck(v.advertiser);
        })
        .subscribe(data => {//process});

    // sequence 2
    this.obs$
        .filter(data => data.hasOwnProperty('orderKey'))
        .mergeMap(() => this.activatedRoute.firstChild.firstChild.url)
        .subscribe(segments => {//process});
}

Upvotes: 3

Related Questions