Reputation: 5017
In AppComponent, I'm trying to read the URL and the params in ngOnInit
and decide where to redirect the user.
I understand that the routes are not instantiated at that point, therefore which I get empty values.
I can use setTimeout
but it is hacky and unreliable. Is there a better way to capture the url and params?
//app.component.ts
constructor(private router: Router) {
//
}
ngOnInit(): void {
setTimeout(() => {
// Get the url to redirect
console.log(">>>> ", this.router.url);
}, 200);
}
Upvotes: 0
Views: 361
Reputation: 27353
You can listen router events and find out the NavigationEnd to perform url extractions instead of using setTimeOut.
ngOnInit() {
this.router.events.subscribe(event => {
if(event instanceof NavigationEnd) {
console.log(this.router.url);
}
});
}
Upvotes: 1