user1496093
user1496093

Reputation: 189

Angular 4/5: avoiding double subscribe

I need to capture a query parameter and then subscribe to an API to return results. I have done this using combineLatest but it seems overkill. Is there a way to simplify this please as I'm not needing to combine more than queryParamMap?

ngOnInit() {
  Observable.combineLatest([
    this.route.queryParamMap
  ])
  .switchMap(combined => {
    let page = combined[0].get('page');

    return this.service.getAll(); //{ page: page}
  })
  .subscribe(results => this.results = results.results);
}

Upvotes: 0

Views: 301

Answers (2)

user1496093
user1496093

Reputation: 189

this.route.queryParamMap
  .switchMap(combined => {
  let page = +combined.get('page');
  return this.service.getAll()
})
.subscribe(
  results => this.results = results.results
);

Thanks for the replies.

Upvotes: 1

user4676340
user4676340

Reputation:

Sure, a simple

this.route.paramMap.switchMap((params: ParamMap) => {
  let page = +params.id.get('page');
  this.service.getAll().subscribe(x => { /* ... */);
});

Should do the trick !

Upvotes: 0

Related Questions