How to handle query parameters in angular 2
RouteParams are now deprecated , So here is how to do it in the new router.
this.router.navigate(['/login'],{ queryParams: { token:'1234'}})
And then in the login component you can take the parameter,
constructor(private route: ActivatedRoute) {}
ngOnInit() {
// Capture the token if available
this.sessionId = this.route.queryParams['token']
}
Here is the documentation
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
UPDATE: After changes in router alpha.31 http query params no longer work (Matrix params #2774). Instead angular router uses so called Matrix URL notation.
Reference https://angular.io/docs/ts/latest/guide/router.html#!#optional-route-parameters:
The optional route parameters are not separated by "?" and "&" as they would be in the URL query string. They are separated by semicolons ";" This is matrix URL notation — something you may not have seen before.