Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular 2 Routing based on query params

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.

like image 776
Manuel Mauky Avatar asked Feb 17 '17 13:02

Manuel Mauky


Video Answer


2 Answers

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

like image 63
Teddy Sterne Avatar answered Oct 25 '22 21:10

Teddy Sterne


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' } });
}
like image 25
BERGUIGA Mohamed Amine Avatar answered Oct 25 '22 21:10

BERGUIGA Mohamed Amine