cant get the param route angular 6

Viewed 2620

I'm trying to get the [param] from url, and get some information throw a service with this param, and then (ONLY then) go to another page.

Chome URL: http://localhost:4200/login/asd

appmodule:

{ path: 'login/:token', component: AppComponent},

appcomponent.ts

ngOnInit() {

this.sub = this.route.params.subscribe(params => {
  this.usr = params['token']; 
  console.log(this.usr); //THIS KEEP GETTING UNDEFINED

});
}

That usr keeps getting undefined, dont know why... Some idea? Thanks.

I tryied things like this:

this.sub = this.route.params.subscribe(params => {
  if (!params['token']) { 
    console.log('NO token'); //GOES HERE EVERYTIME
     }
  this.token = params['token'];
  console.log(this.token);
});

It gets out in 'NO token' every single time.. Something wrong with the url maybe?

1 Answers

There is another question opened that describes your issue. This is related to ActivatedRoute state outside of arouter-outlet, in your case I believe you don't have it.

I did a test in stackbliz where you can see it working with router-outlet, but to do this I had to change the router path to another component(The AppComponent is the root component, so I did not use it).

Here is the stackblitz example:

https://stackblitz.com/edit/angular-izk361

And here much more info about this problem.

Angular 2 Activatedroute params not working in Service or outside <router-outlet>

Related