在Angular 2中检索参数和queryParams的最佳实践 [英] Best practice of retrieving params and queryParams in Angular 2
问题描述
我试图了解创建路由的方式,并在URL参数中包含一些信息.
I'm trying to understand the way of creating a route, with some information in it's URL parameters.
这是我的路线(app.routes.ts):
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 } });}
如您所见,我还有一个查询参数.我想知道,在我的MyResultsComponent
中检索此内容的最佳和最干净的方法是什么.现在,我有一个嵌套的subscribe
结构:
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);
});
});
}
然后,我想将此参数传递给我的EntryService
,它返回找到的条目.
Afterwards, I want to pass this parameters to my EntryService
, which returns the found entries.
推荐答案
使用forkJoin怎么样?
What about using a forkJoin?
ForkJoin允许您加入两个可观察对象,并等待它们的响应.您可以在此处 a>并在此处了解更多信息.
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);
});
}
您可能需要添加导入:
import { Observable } from 'rxjs/Observable';
import 'rxjs/add/observable/forkJoin';
这篇关于在Angular 2中检索参数和queryParams的最佳实践的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!