Search code examples
angularangular-routingangular-router-guards

Angular Routing to the wrong path when redirected


Angular 8.2.14

So I have a problem with my angular routing, here is the code from my routing-module:

  { 
    path: "hero", 
    component: HeroListComponent, 
    canActivate: [AuthGuard], 
    children: [
      { 
        path: "new", 
        component: NewHeroComponent
      },
      { 
        path: ":id", 
        component: HeroComponent, 
        canActivate: [HeroGuard]
      }
    ],
  },

My problem is that I have a button on another website that redirects me to my Angular app, when the button is clicked, it opens a new tab with a url like this:

http://localhost:4200/hero/new?power=123&attr=123%20456%20789&city=123&rt=1&rate=80

When the user is already logged in, the routing module works fine and brings him to the NewHeroComponent properly and handles the params of the query correctly.

The problem occurs when the user isn't logged in and has to go through the authentication process, normally the redirection is done without any problem for the other components but for some reason in this case the router tries to open the HeroComponent.

When I log the ActivatedRouteSnapshot in my HeroGuard (which isn't supposed to be called but still is) I get this:

params:
  id: "new?power=123&attr=123%20456%20789&city=123&rt=1&rate=80"

The redirection is pretty simple, the link is kept in localStorage when the user isn't logged in and the redirection is done in my main component after the user logs in if the localStorage key for my redirection is set by using this.router.navigate([route]).

Thank you in advance for your help!


Solution

  • After more research, I found that I used the wrong function to navigate.

    The problem: the ? in the url was changed for %3F when router.navigate([route]) was called, result of this was that angular thought it was a parameter.

    The solution: I changed router.navigate([route]) to router.navigateByUrl(route)