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
?
The query parameters feature in Angular lets you pass the optional parameters while navigating from one route to another. When you pass a query parameter to a specific route, it looks something like this, http://localhost:4200/orders? category=watches.
Use queryParamMap to access query parameters. Another way to access query paramters in Angular is to use queryParamMap property of ActivatedRoute class, which returns an observable with a paramMap object.
Using queryParamsHanding property we can preserve or merge query parameters in Angular. In Angular, query parameters are lost when we navigate from one route to another route.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With