Angular router - Get Target-URL of current navigation process

Viewed 1338

I have an NG-module with nested routing.

  • Main.module with main.component
  • Sub.module with sub.component

Pathes look like this: http://domain/mainroute/nestedroute

Now, in the sub.component i want to make a decision for rerouting based on the target-URL that was provided (by user or external redirect). So if a user targets a nested route directly, I want to check if i let him pass or if i redirect him to a different location. For that, i need to find out the URL that was typed in when initializing the sub.component.

However, in the sub.component:

constructer(private router: Router){
    console.log(this.router.url)
}

the log returns http://domain/mainroute even though http://domain/mainroute/nestedroute was typed in and gets directed to. This might be because the navigation process runs the constructor of sub.component before doing further routing.

now the question is: how can i access the full route at this point?

1 Answers

If you want to prevent entering to route under specified circumstances I suggest using angular guards. It's router based mechanism designed for such needs.

If the problem is just getting target url address I'm afraid this data is not available in angular router, but you can use window.location.href

Related