I'm trying to understand the way of creating a route, with some information in it's URL parameters.
This is my route (app.routes.ts):
{path: 'results/:id', component: MyResultsComponent},
This is how I navigate to the route :
goToResultsPage(query: string) {
this.router.navigate(['results', query], { queryParams: { pageSize: 20 } });}
As you can see, I've also a query parameter. I was wondering, what is the best and cleanest way to retrieve this in my MyResultsComponent
. Right now I've kind of a nested subscribe
structure:
ngOnInit() {
this.route
.params
.subscribe(params => {
this.query = params['id'];
this.route
.queryParams
.subscribe(queryParams => {
this.offset = queryParams['pageSize'];
#find entries this.entryService.findEntries(this.query, this.pageSize);
});
});
}
Afterwards, I want to pass this parameters to my EntryService
, which returns the found entries.
What about using a forkJoin?
ForkJoin allows you to join two observables and wait for the response of both them. You can see the documentation here and read more about it here.
As for your code it would look something like this:
ngOnInit() {
Observable.forkJoin(this.route.params, this.route.queryParams).subscribe(bothParams => {
// bothParams is an array, on the first index we have the router.params
// on the second index we have the queryParams
this.query = bothParams[0].query;
this.pageSize = bothParams[0].pageSize;
this.entryService.findEntries(this.query, this.pageSize);
});
}
You might need to add imports:
import { Observable } from 'rxjs/Observable';
import 'rxjs/add/observable/forkJoin';