0

I am really confused by the Angular 7 router. I want to use the get parameter "token" from any place in the URL.

I use the following code to define several routes.

const myRoutes: Routes = [
{ path: 'register/:token', component: RegisterComponent },
// { path: 'register?token=:token', component: RegisterComponent },
// { path: 'register:token', component: RegisterComponent },
{ path: 'register', component: RegisterComponent },
// ...
]

With the first defined path I am able to use "register/mytoken" and "register/?token=mytoken" to get the token.

// Token from register/123
this.token = this.route.snapshot.paramMap.get('token')
// Token from register/?token=123
this.route.queryParams.subscribe(params => {
  if (params.token != null)
    this.token = params.token;
});

Any time i try to provide my token directly as get-parameter when calling the website in my browser ("register?token=mytoken"), the router will redirect me to "/register" and I can't get the token with my code above. But when i use "register/?token=mytoken" i will be redirected to "register?token=mytoken" and can use the token.

How can i provide a route for accessing the page with "register?token=123" and retrieve the token?

Celdus
  • 1,010
  • 1
  • 14
  • 25
  • 1
    Tested your code and it works with `http://localhost:4200/register?token=123` and `http://localhost:4200/register/?token=123` for me. So the code you give doesn't seems to be the problem. But just in case, did you try to change order of these paths ? – Gilsdav Dec 08 '18 at 21:14

1 Answers1

0

Thanks to @Gilsdav, I should have tested this in a "clean" project by myself. I found some block of code from my colleague, which interferes with the get parameter of the router:

var loc = window.location.pathname;    
if ((loc == "/register") || (loc == "/"))  {
  this.router.navigate(['/landing']);
}

This redirect strips the get parameters. I could verify the redirect by his code by adding {enableTracing:true}.

imports: [
    RouterModule.forRoot(
      routes,
      { enableTracing: true } // <-- debugging purposes only
    )
]
Celdus
  • 1,010
  • 1
  • 14
  • 25