在 Angular 2 中检索 params 和 queryParams 的最佳实践 [英] Best practice of retrieving params and queryParams in Angular 2

查看:25
本文介绍了在 Angular 2 中检索 params 和 queryParams 的最佳实践的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图了解创建路由的方式,在它的 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 允许你加入两个 observable 并等待它们的响应.您可以在此处查看文档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 中检索 params 和 queryParams 的最佳实践的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆