[javascript] 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?

This question is related to javascript jquery angular angular2-routing

The answer is


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');
   }
}

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']

}

It seems that RouteParams no longer exists, and is replaced by ActivatedRoute. ActivatedRoute gives us access to the matrix URL notation Parameters. If we want to get Query string ? paramaters we need to use Router.RouterState. The traditional query string paramaters 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 that is attached to the latest router documentation 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);

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


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


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;

(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


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


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']

}

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


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>

Examples related to javascript

need to add a class to an element How to make a variable accessible outside a function? Hide Signs that Meteor.js was Used How to create a showdown.js markdown extension Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Summing radio input values How to execute an action before close metro app WinJS javascript, for loop defines a dynamic variable name Getting all files in directory with ajax

Examples related to jquery

How to make a variable accessible outside a function? Jquery assiging class to th in a table Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Getting all files in directory with ajax Bootstrap 4 multiselect dropdown Cross-Origin Read Blocking (CORB) bootstrap 4 file input doesn't show the file name Jquery AJAX: No 'Access-Control-Allow-Origin' header is present on the requested resource how to remove json object key and value.?

Examples related to angular

error NG6002: Appears in the NgModule.imports of AppModule, but could not be resolved to an NgModule class error TS1086: An accessor cannot be declared in an ambient context in Angular 9 TS1086: An accessor cannot be declared in ambient context @angular/material/index.d.ts' is not a module Why powershell does not run Angular commands? error: This is probably not a problem with npm. There is likely additional logging output above Angular @ViewChild() error: Expected 2 arguments, but got 1 Schema validation failed with the following errors: Data path ".builders['app-shell']" should have required property 'class' Access blocked by CORS policy: Response to preflight request doesn't pass access control check origin 'http://localhost:4200' has been blocked by CORS policy in Angular7

Examples related to angular2-routing

'router-outlet' is not a known element How to reload page the page with pagination in Angular 2? Error: Cannot match any routes. URL Segment: - Angular 2 Can't bind to 'routerLink' since it isn't a known property Passing data into "router-outlet" child components How to determine previous page URL in Angular? How to get parameter on Angular2 route in Angular way? Angular 2 Scroll to top on Route Change Angular routerLink does not navigate to the corresponding component Angular 2 router.navigate