Reputation: 225
I'm trying to create pagination for an angular 2 web app with query parameters and observables. I've gotten things to work with the code below, but I have a feeling that nesting the subscriptions isn't a good idea. Is there a better way to do this?
blogs:any;
page = 0;
sub;
ngOnInit() {
this.sub = this.route.queryParams
.subscribe(params => {
this.page = +params['page'] || 0;
this.requestService.getData('posts', '..query string...')
.subscribe(data => this.blogs = data.data);
});
}
nextPage() {
this.router.navigate(['./'], { queryParams: { page: this.page + 1 }, relativeTo: this.route } );
}
Upvotes: 2
Views: 428
Reputation: 136174
You could use .switchMap
to chain observable.
ngOnInit() {
this.sub = this.route.queryParams
.switchMap(params => {
this.page = +params['page'] || 0;
return this.requestService.getData('posts', '..query string...')
})
.subscribe(data => this.blogs = data.data);
}
Upvotes: 2