In my real world application I want to check in the startup component (usually app.component.ts) if a user is authenticated. If not, I want to route them to the login component. But routing doesn't work here.
I create a simple Plunker example, where it is reproduceable:
- Open live example
- Click the button "navigate to sample 1" --> everything works
- But you can see, that I have the same routing command already in the
app/app.component.ts
- but the application doesn't route to the component. Why??
Thanks for your help!
If you wrap it with
setTimeout()
it's working finePlunker example
It seems the default routing takes place after your call to
router.navigate()
and therefore doesn't take effect.I'm sure there are better ways to achieve the same instead of
setTimout()
but I think it's fine to demonstrate the issue.For example this would result in the same behavior
You can also use a
canActivate
guard for the default route and do therouter.navigate()
there.