Search code examples
angularangular2-routing

get current url outside of router-outlet


I want to get current url. For that I'm doing

constructor(public router: Router) { ... }
ngOnInit() { console.log(this.router.url); }

and it works ok. But now I want to move it to layout component which is parent of every component. And I have <router-outlet></router-outlet> inside of layoutcomponent.

When I log this code inside of layout component it logs: /

what can I do?


Solution

  • You can use a Router event and subscribe to it

    constructor(router: Router) {
        this.router.events.subscribe((event: Event) => {
            console.log(event.url); // This will give you the required url
        });
    }