3

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?

9
  • Cannot match any routes when I try that. Commented Jan 12, 2019 at 19:56
  • you have private route: ActivatedRoute in the constructor right? just to make sure Commented Jan 12, 2019 at 20:03
  • Yes sir I have: private route: ActivatedRoute Commented Jan 12, 2019 at 20:07
  • Please, test this url, just to be sure: localhost:4200/login/40 Commented Jan 12, 2019 at 20:26
  • Same result Sir. Keep getting undefined. I dont understand why.. I used params in other places and works just fine.. Commented Jan 12, 2019 at 20:29

1 Answer 1

4

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>

Sign up to request clarification or add additional context in comments.

1 Comment

YES SR! You were right. For some reason the params dont work outside the router-outlet. I move the login to other component, and get the params correctly. Thank you!

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.