Angular 2: One path for multiple components?

Viewed 410

I am trying to create a route on Angular 8 where a certain path has a public and private version so if i input /tracker in the URL the routing module can send me to the private/public version depending on if i am logged in or logged out.

I have tried Guards with CanActivate but this just stops the navigation if i return false, and i specifically need that both routes have the same path. This is my routing module:

    path: '',
    children: [
      {
        path: '',
        canActivate: [AuthGuard],
        component: TrackingListPrivateComponent
      },
      {
        path: '',
        component: TrackingListComponent
      }
    ]
  }

I expect to be able to input /tracker on the URL while being logged out and navigate to TrackingListComponent and after logged in to input /tracker on the URL and navigate to TrackingListPrivateComponent.

1 Answers

It's not a good practice to have the same route twice in the routing configuration, I'm not even sure if it's technically possible at all.

In your case I'd create only one route for "/tracker" and handle the "logged in" or "logged out" status in an intermediate component:

{
    path: 'tracker',
    component: TrackingListComponent
}

In the template of the intermediate component you can call either the public or private component depending on the "loggedIn" status:

<app-tracking-list *ngIf="!loggedIn"></app-tracking-list>
<app-private-tracking-list *ngIf="loggedIn"></app-private-tracking-list>

Your intermediate TrackingListComponent needs a function that returns the loggedIn status:

class TrackingListComponent {
    /** Return login status */
    get loggedIn(): boolean {
        return this.loginService.loggedIn;
    }
}
Related