angular 4 how to get url parameters
First, set the ActivatedRoute
in your constructor
constructor(private route: ActivatedRoute){}
public user:your_type;
Secondly, put this code in constructor callback:
this.route.params.subscribe(params => { this.user = params['user']; });
This method will work if you use the following code to redirect:
this.router.navigate(['./yourlocation', { user: this.user }]);
Modifed
Angular Url structure is a/:paras1/:paras2
or a?a=3;
without using &
.
If you use &
to separate your parameters, it is recommended to use nativeJS to get.
constructor(){
this.user = this.getUrlParameter('user');
}
public user;
private getUrlParameter(sParam) {
return decodeURIComponent(window.location.search.substring(1)).split('&')
.map((v) => { return v.split("=") })
.filter((v) => { return (v[0] === sParam) ? true : false })
.reduce((prev, curv, index, array) => { return curv[1]; }, undefined);
};
If you want to use query params and not define them in route, you can reference ActivatedRoute in your constructor and subscribe to queryParams.
constructor(private route: ActivatedRoute) {
this.route
.queryParams
.subscribe(params => {
// here you can access params['user'], params['token'], etc.
});
}
By using ActivatedRoute snapshot as below example.
this.userName = this.activatedRoute.snapshot.params['user'];
this.userToken = this.activatedRoute.snapshot.params['token'];
this.userPicture = this.activatedRoute.snapshot.params['picture'];