snippettypescriptangularCritical
How to get query params from url in Angular 2?
Viewed 0 times
angularurlhowparamsfromgetquery
Problem
I use angular2.0.0-beta.7. When a component is loaded on a path like
I have an error in the routers. If I have a main route like
and my child route like
then I can't get params in TodoListComponent. I am able to get
but I want the classic
/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
By injecting an instance of
A NOTE REGARDING UNSUBSCRIBING
@Reto and @codef0rmer had quite rightly pointed out that, as per the official docs, an
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)Code Snippets
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);
});
}
}Context
Stack Overflow Q#35688084, score: 486
Revisions (0)
No revisions yet.