How can I get the query params from URL in Angular 2

7,175 views
Skip to first unread message

Guilherme Fritsch

unread,
Jun 23, 2016, 7:58:49 AM6/23/16
to AngularJS
Hi!

We are trying to start using Angular 2 in our product, but somethings blocking us to do this.

Just to exemplify: we need to can use an URL like this:   weproject.abc:4200/login?param1=nick&token=123iajdd098fsd90faf

So, how can I get the "param1" and "nick" params value?
We try to use something like

(...)
this.sub = this.router
 .routerState 
 .queryParams
 .subscribe(params => { 
 this.selectedId = +params['id']; 
 this.service.getHeroes() 
.then(heroes => this.heroes = heroes); });

But nor 'nick' or 'param1' was found in 'params[]'. I think that Route params that we will find there are only that we was setted in routes config. 
So, how can I get this 'others' url params?

 


HisDivineShadow

unread,
Jun 27, 2016, 10:17:55 AM6/27/16
to AngularJS
I just went through the same thing and the example on Angular's (latest) routing example page didn't work for me either.  The funny thing is, the code in the tutorial is different from the Plnker that they point to from the tutorial as the LIVE example, and neither works.  I finally found an example that works.

I'm using the v3 router (3.0.0-alpha.7) here so make sure that you're using that otherwise i don't know what you'll get.

In your component use the following import  

import {Router, ROUTER_DIRECTIVES, ActivatedRoute} from '@angular/router';


Then in your component's constructor inject this:

constructor(private router: Router, private activatedRoute: ActivatedRoute) {    }


Then create component variable:

    paramsSub: any;


Next, in the ngOnInit do this:

ngOnInit() {
this.paramsSub = this.activatedRoute.params.subscribe(params => {
        this.homeId = +params['homeId'];  //get your param
        call your function that needs the route param
        });
}
 
Finally, in ngOnDestroy

ngOnDestroy() {
    this.paramsSub.unsubscribe();
}

Reply all
Reply to author
Forward
0 new messages