Search code examples
angularangular-routingangular-rc5

Angular 2 (RC6) - Routing in the startup component doesn'n work


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:

  1. Open live example
  2. Click the button "navigate to sample 1" --> everything works
  3. 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!


Solution

  • If you wrap it with setTimeout() it's working fine

    setTimeout(() => {
      this.router.navigate(["/sample1", "2"]);
    });
    

    Plunker 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

    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.