Angular 2 Routing based on query params

心不动则不痛 提交于 2019-12-19 02:32:29

问题


Is it possible in Angular 2 to define routing based on query parameters? I'd like to have the following behaviour:

If the user enteres the url http:<server-path>/search I'd like to route to a StartPage component.

If the user enteres the url http:<server-path>/search?query=sometext I'd like to route to ResultList component.

I know that it's possible to use path parameters for routing but this is not what I like to do. I want to use query parameters if possible. I know how to trigger navigation in angular with query parameters but I don't know how to configure the Routes.


回答1:


So you can't define a path with the query string in it but you can use a route matcher instead and determine when to route to the ResultList component. You define this above the default route definition for search so that if the match fails it will default to the search route with no query string.

{
    component: ResultListComponent,
    matcher: (url: UrlSegment[]) => {
      console.log(url);
      return url.length === 1 && url[0].path.indexOf('search?query=') > -1 ? ({consumed: url}) : null;
    }
},
{
    path: 'search',
    component: SearchComponent,
}

Demo




回答2:


In the below code I'll show how to pass query string parameters across any route.

suppose we want to have the below url:

http://localhost:4200/myUrl?QueryParamEx=2258

In your constructor inject the ROUTER dependency

constructor(...private router: Router..){...}

The navigate function will allow us to navigate to the preceding url

goMyUrl() {
  this.router.navigate(['/myUrl'], { queryParams: { QueryParamEx: '2258' } });
}



回答3:


You can also setup something like this:

Routes:

{ path: 'server-path/:id', component: ResultListComponent },
{ path: 'server-path', component: serverPathComponent },

ResultListComponent

queryParam: string;
    ngOnInit() {     
           this.route.params.forEach((params: Params) => {
               this.queryParam = params['id'];

           });
       }

You can call whatever function or anything that you need to do using that queryParam.

More on query params can be found at the Routing & Navigation guide



来源:https://stackoverflow.com/questions/42299753/angular-2-routing-based-on-query-params

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!