Reputation: 78234
How does one get query parameters in Angular 2 RC4? I tried the docs and they make no sense whatsoever.
e.g.
http://localhost:3000/models/initials/mid_c1e1c31e6eff42f1982af4124a823b36?test=4
In ngOnInit
how do I get the value of the parameter test
?
private sub: Subscription;
ngOnInit() {
this.sub = this.route.params.subscribe(params => {
console.log(params);
let id = params['test'];
console.log(id);
});
}
This is how I navigate to the route where I want to get the query parms:
this._router.navigate(['models/initials/'+model_id+'?test=4']);
Upvotes: 1
Views: 2055
Reputation: 3771
can be done in this way which uses Javascript :
(new URL(location)).searchParams.get("parameter_name")
Upvotes: -1
Reputation: 441
The OP asked about query parameters, the correct way to do this is to use the queryParams object off of the route.
ngOnInit() {
this.sub = this.route.queryParams.subscribe(params => {
console.log(params);
let id = params['test'];
console.log(id);
})
}
This is different than the params object which the other answers reference.
I'd also recommend using the NavigationExtras object to add to the query string correctly per: https://angular.io/docs/ts/latest/guide/router.html down in the "Query Parameters and Fragments" section.
Upvotes: 5
Reputation: 1763
constructor(private route:ActivatedRoute) {}
ngOnInit() {
this.route.params.map(params => params['test'])
.subscribe(id => { /* do what you want with the id */ });
Upvotes: 3
Reputation: 1217
You have to use ActivatedRoute:
private sub: Subscription;
constructor(private router: Router, private activatedRoute: ActivatedRoute){}
ngOnInit() {
this.sub = this.activatedRoute.params.subscribe(
(param: any) => this.test = param['test']
)
}
Upvotes: 0
Reputation: 10603
Have you tried RouteSegment
routerOnActivate(curr: RouteSegment) {
this.userName = curr.getParam('userName');
this.projId = curr.getParam('projId');
}
Upvotes: -1