Reputation: 613
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:
app/app.component.ts
- but the application doesn't route to the component. Why??Thanks for your help!
Upvotes: 1
Views: 458
Reputation: 657721
If you wrap it with setTimeout()
it's working fine
setTimeout(() => {
this.router.navigate(["/sample1", "2"]);
});
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
RouterModule.forRoot([
{ path: "", redirectTo: '/sample1/2', pathMatch: 'full' }
{ path: "sample1/:param1", component: Sample1Component },
{ path: "**", component: HomeComponent }
])
You can also use a canActivate
guard for the default route and do the router.navigate()
there.
Upvotes: 1