How to handle query parameters in angular 2

JavascriptJqueryAngularAngular2 Routing

Javascript Problem Overview


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?

Javascript Solutions


Solution 1 - Javascript

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

Solution 2 - Javascript

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.

Solution 3 - Javascript

It seems that RouteParams no longer exists, and is replaced by [ActivatedRoute][1]. ActivatedRoute gives us access to the matrix URL notation Parameters. If we want to get Query string ? paramaters we need to use [Router.RouterState][2]. The [traditional query string paramaters][3] are persisted across routing, which may not be the desired result. Preserving the fragment is now optional in router 3.0.0-rc.1.

import { Router, ActivatedRoute } from '@angular/router';
@Component ({...})
export class paramaterDemo {
  private queryParamaterValue: string;
  private matrixParamaterValue: string;
  private querySub: any;
  private matrixSub: any;
  
  constructor(private router: Router, private route: ActivatedRoute) { }
  ngOnInit() {
    this.router.routerState.snapshot.queryParams["queryParamaterName"];
    this.querySub = this.router.routerState.queryParams.subscribe(queryParams => 
      this.queryParamaterValue = queryParams["queryParameterName"];
    );

    this.route.snapshot.params["matrixParameterName"];
    this.route.params.subscribe(matrixParams =>
      this.matrixParamterValue = matrixParams["matrixParameterName"];
    );
  }

  ngOnDestroy() {
    if (this.querySub) {
      this.querySub.unsubscribe();
    }
    if (this.matrixSub) {
      this.matrixSub.unsubscribe();
    }
  }
}

We should be able to manipulate the ? notation upon navigation, as well as the ; notation, but I only gotten the matrix notation to work yet. The [plnker][4] that is attached to the latest [router documentation][5] shows it should look like this.

let sessionId = 123456789;
let navigationExtras = {
  queryParams: { 'session_id': sessionId },
  fragment: 'anchor'
};

// Navigate to the login page with extras
this.router.navigate(['/login'], navigationExtras);

[1]: https://angular.io/docs/js/latest/api/router/index/ActivatedRoute-interface.html "ActivateRoute" [2]: https://angular.io/docs/js/latest/api/router/index/Router-class.html "Router" [3]: https://angular.io/docs/ts/latest/guide/router.html#!#global-query-parameters-and-fragments "Global Query parameters and Fragments" [4]: https://angular.io/resources/live-examples/router/ts/plnkr.html "Hero example" [5]: https://angular.io/docs/ts/latest/guide/router.html "Routing & Navigation"

Solution 4 - Javascript

This worked for me (as of Angular 2.1.0):

constructor(private route: ActivatedRoute) {}
ngOnInit() {
  // Capture the token  if available
  this.sessionId = this.route.snapshot.queryParams['token']

}

Solution 5 - Javascript

(For Childs Route Only such as /hello-world)

In the case you would like to make this kind of call :

/hello-world?foo=bar&fruit=banana

Angular2 doesn't use ? nor & but ; instead. So the correct URL should be :

/hello-world;foo=bar;fruit=banana

And to get those data :

import { Router, ActivatedRoute, Params } from '@angular/router';

private foo: string;
private fruit: string;

constructor(
  private route: ActivatedRoute,
  private router: Router
  ) {}

ngOnInit() {
  this.route.params.forEach((params: Params) => {
      this.foo = params['foo'];
      this.fruit = params['fruit'];
  });
  console.log(this.foo, this.fruit); // you should get your parameters here
}

Source : https://angular.io/docs/ts/latest/guide/router.html

Solution 6 - Javascript

Angular2 v2.1.0 (stable):

The ActivatedRoute provides an observable one can subscribe.

  constructor(
     private route: ActivatedRoute
  ) { }

  this.route.params.subscribe(params => {
     let value = params[key];
  });

This triggers everytime the route gets updated, as well: /home/files/123 -> /home/files/321

Solution 7 - Javascript

The simple way to do that in Angular 7+ is to:

Define a path in your ?-routing.module.ts

{ path: '/yourpage', component: component-name }

Import the ActivateRoute and Router module in your component and inject them in the constructor

contructor(private route: ActivateRoute, private router: Router){ ... }

Subscribe the ActivateRoute to the ngOnInit

ngOnInit() {
    
    this.route.queryParams.subscribe(params => {
      console.log(params);
      // {page: '2' }
    })
}

Provide it to a link:

<a [routerLink]="['/yourpage']" [queryParams]="{ page: 2 }">2</a>

Solution 8 - Javascript

Angular 4:

I have included JS (for OG's) and TS versions below.

.html

<a [routerLink]="['/search', { tag: 'fish' } ]">A link</a>

In the above I am using the link parameter array see sources below for more information.

routing.js

(function(app) {
    app.routing = ng.router.RouterModule.forRoot([
        { path: '', component: indexComponent },
        { path: 'search', component: searchComponent }
    ]);
})(window.app || (window.app = {}));

searchComponent.js

(function(app) {
    app.searchComponent =
        ng.core.Component({
            selector: 'search',
                templateUrl: 'view/search.html'
            })
            .Class({
                constructor: [ ng.router.Router, ng.router.ActivatedRoute, function(router, activatedRoute) {
                // Pull out the params with activatedRoute...
                console.log(' params', activatedRoute.snapshot.params);
                // Object {tag: "fish"}
            }]
        }
    });
})(window.app || (window.app = {}));

routing.ts (excerpt)

const appRoutes: Routes = [
  { path: '', component: IndexComponent },
  { path: 'search', component: SearchComponent }
];
@NgModule({
  imports: [
    RouterModule.forRoot(appRoutes)
    // other imports here
  ],
  ...
})
export class AppModule { }

searchComponent.ts

import 'rxjs/add/operator/switchMap';
import { OnInit } from '@angular/core';
import { Router, ActivatedRoute, Params } from '@angular/router';

export class SearchComponent implements OnInit {

constructor(
   private route: ActivatedRoute,
   private router: Router
) {}
ngOnInit() {
    this.route.params
      .switchMap((params: Params) => doSomething(params['tag']))
 }

More infos:

"Link Parameter Array" https://angular.io/docs/ts/latest/guide/router.html#!#link-parameters-array

"Activated Route - the one stop shop for route info" https://angular.io/docs/ts/latest/guide/router.html#!#activated-route

Solution 9 - Javascript

For Angular 4

Url:

http://example.com/company/100

Router Path :

const routes: Routes = [
  { path: 'company/:companyId', component: CompanyDetailsComponent},
    
]

Component:

@Component({
  selector: 'company-details',
  templateUrl: './company.details.component.html',
  styleUrls: ['./company.component.css']
})
export class CompanyDetailsComponent{
   companyId: string;
   
   constructor(private router: Router, private route: ActivatedRoute) {
          this.route.params.subscribe(params => {
          this.companyId = params.companyId;
          console.log('companyId :'+this.companyId);
     }); 
  }
}

Console Output:

> companyId : 100

Solution 10 - Javascript

According to Angular2 documentation you should use:

@RouteConfig([
   {path: '/login/:token', name: 'Login', component: LoginComponent},
])

@Component({ template: 'login: {{token}}' })
class LoginComponent{
   token: string;
   constructor(params: RouteParams) {
      this.token = params.get('token');
   }
}

Solution 11 - Javascript

Angular 5+ Update

> The route.snapshot provides the initial value of the route parameter > map. You can access the parameters directly without subscribing or > adding observable operators. It's much simpler to write and read:

Quote from the Angular Docs

To break it down for you, here is how to do it with the new router:

this.router.navigate(['/login'], { queryParams: { token:'1234'} });

And then in the login component (notice the new .snapshot added):

constructor(private route: ActivatedRoute) {}
ngOnInit() {
    this.sessionId = this.route.snapshot.queryParams['token']

}

Solution 12 - Javascript

In Angular 6, I found this simpler way:

navigate(["/yourpage", { "someParamName": "paramValue"}]);

Then in the constructor or in ngInit you can directly use:

let value = this.route.snapshot.params.someParamName;

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
Questionmonty_lennieView Question on Stackoverflow
Solution 1 - JavascriptJayantha Lal SirisenaView Answer on Stackoverflow
Solution 2 - JavascriptThierry TemplierView Answer on Stackoverflow
Solution 3 - JavascriptStephenView Answer on Stackoverflow
Solution 4 - JavascriptbrandoView Answer on Stackoverflow
Solution 5 - JavascriptWetteren RémiView Answer on Stackoverflow
Solution 6 - JavascriptmarcelView Answer on Stackoverflow
Solution 7 - JavascriptFortedxView Answer on Stackoverflow
Solution 8 - JavascriptAllyView Answer on Stackoverflow
Solution 9 - JavascriptAmirView Answer on Stackoverflow
Solution 10 - JavascriptsuvrocView Answer on Stackoverflow
Solution 11 - JavascriptKyle KrzeskiView Answer on Stackoverflow
Solution 12 - JavascriptAndrewView Answer on Stackoverflow