Reputation: 325
Let's say I have a HTML template with following element.
<a [routerLink]="['/final', {issue_id: 2356254}]">SUBMIT</a>
Clicking on this hyperlink will generate a URL like this:
http://localhost:3000/final;issue_id=2356254
I'm trying to access this query parameter inside my component's constructor.
export class FinalComponent {
constructor(private route: ActivatedRoute){
this.issueId = route.params._value.issue_id;
console.log(this.issueId);
}
}
This works so far but I know this isn't the correct method. What is the proper way to access query parameters inside an Angular 2 Component?
Upvotes: 0
Views: 103
Reputation: 1174
Using ActivatedRoute
is a good start.
You can subscribe to params
property since it is a Observable
:
constructor(private route: ActivatedRoute) { }
ngOnInit() {
this.route.params.subscribe(params => {
// access route params
console.log(params['id']);
});
}
Sample on GitHub
route.snapshot
If you are not interested in changes of the parameter you can simply use this.route.snapshot.params
. So you do not have to handle with Observables.
Sample
constructor(route: ActivatedRoute) {
let id = route.snapshot.params['id];
}
Upvotes: 1