Mlennie Mlennie - 4 months ago 21
Javascript Question

How to handle query parameters in angular 2

In my

routable component
I have

@RouteConfig {
{path: '/login', name: 'Login', component: LoginComponent}
}


but how do I get the query params if I go to
app_url/login?token=1234
?

Answer

To complement the two previous answers, Angular2 supports both query parameters and path variables within routing. In @RouteConfig definition, if you define parameters within a path, Angular2 handles them as path variables and as query parameters if not.

Let's take a sample:

@RouteConfig([
  { path: '/:id', component: DetailsComponent, name: 'Details'}
])

If you call the navigate method of the router like this:

this.router.navigate( [
  'Details', { id: 'companyId', param1: 'value1'
}]);

You will have the following address: /companyId?param1=value1. The way to get parameters is the same for both, query parameters and path variables. The difference between them is that path variables can be seen as mandatory parameters and query parameters as optional ones.

Hope it helps you, Thierry

Comments