How to get query params from url in Angular 2?
I use angular2.0.0-beta.7. When a component is loaded on a path like /path?query=value1
it is redirected to /path
. Why were the GET params removed? How can I preserve the parameters?
I have an error in the routers. If I have a main route like
@RouteConfig([
{
path: '/todos/...',
name: 'TodoMain',
component: TodoMainComponent
}
])
and my child route like
@RouteConfig([
{ path: '/', component: TodoListComponent, name: 'TodoList', useAsDefault:true },
{ path: '/:id', component: TodoDetailComponent, name:'TodoDetail' }
])
then I can't get params in TodoListComponent. I am able to get
params("/my/path;param1=value1;param2=value2")
but I want the classic
query params("/my/path?param1=value1¶m2=value2")
Solution 1:
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)
Solution 2:
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"];
}
}
Solution 3:
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.
Solution 4:
I really liked @StevePaul's answer but we can do the same without extraneous subscribe/unsubscribe call.
import { ActivatedRoute } from '@angular/router';
constructor(private activatedRoute: ActivatedRoute) {
let params: any = this.activatedRoute.snapshot.params;
console.log(params.id);
// or shortcut Type Casting
// (<any> this.activatedRoute.snapshot.params).id
}