Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 634
monty_lennie Avatar asked Jan 04 '16 20:01

monty_lennie


People also ask

What is query parameters in Angular?

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.

How do I get query parameters in Angular 13?

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.

Why we use query parameters in Angular?

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.


2 Answers

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

like image 136
Jayantha Lal Sirisena Avatar answered Sep 21 '22 13:09

Jayantha Lal Sirisena


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.

like image 36
Thierry Templier Avatar answered Sep 21 '22 13:09

Thierry Templier