How to get query params from url in Angular 2?
By injecting an instance of ActivatedRoute
one can subscribe to a variety of observables, including a queryParams
and a params
observable:
import {Router, ActivatedRoute, Params} from '@angular/router';
import {OnInit, Component} from '@angular/core';
@Component({...})
export class MyComponent implements OnInit {
constructor(private activatedRoute: ActivatedRoute) {}
ngOnInit() {
// Note: Below 'queryParams' can be replaced with 'params' depending on your requirements
this.activatedRoute.queryParams.subscribe(params => {
const userId = params['userId'];
console.log(userId);
});
}
}
A NOTE REGARDING UNSUBSCRIBING
@Reto and @codef0rmer had quite rightly pointed out that, as per the official docs, an unsubscribe()
inside the components onDestroy()
method is unnecessary in this instance. This has been removed from my code sample. (see blue alert box in this tutorial)
Even though the question specifies version beta 7, this question also comes up as top search result on Google for common phrases like angular 2 query parameters. For that reason here's an answer for the newest router (currently in alpha.7).
The way the params are read has changed dramatically. First you need to inject dependency called Router
in your constructor parameters like:
constructor(private router: Router) { }
and after that we can subscribe for the query parameters on our ngOnInit
method (constructor is okay too, but ngOnInit
should be used for testability) like
this.router
.routerState
.queryParams
.subscribe(params => {
this.selectedId = +params['id'];
});
In this example we read the query param id from URL like example.com?id=41
.
There are still few things to notice:
- Accessing property of
params
likeparams['id']
always returns a string, and this can be converted to number by prefixing it with+
. - The reason why the query params are fetched with observable is that it allows re-using the same component instance instead of loading a new one. Each time query param is changed, it will cause a new event that we have subscribed for and thus we can react on changes accordingly.
When a URL is like this http://stackoverflow.com?param1=value
You can get the param 1 by the following code:
import { Component, OnInit } from '@angular/core';
import { Router, ActivatedRoute, Params } from '@angular/router';
@Component({
selector: '',
templateUrl: './abc.html',
styleUrls: ['./abc.less']
})
export class AbcComponent implements OnInit {
constructor(private route: ActivatedRoute) { }
ngOnInit() {
// get param
let param1 = this.route.snapshot.queryParams["param1"];
}
}