Reputation: 3731
I want to have multiple components associated to the root path in order to display one landing page view for anonymous users and an inbox for the authenticated users, without having to use manual navigation and path changes crutches.
I've tried to enable my scenario with a routing block like this:
{ path: '', component: LandingComponent, canActivate: [ ForbidAuthGuard ] },
{ path: '', component: LocationsComponent, canActivate: [ RequireAuthGuard ] }
Angular is indeed calling ForbidAuthGuard
, which is failing on an authenticated user and therefore cancelling the navigation event altogether, ignoring the RequireAuthGuard
route.
As implied by their conflicting names both guards are exclusive to each other so only one of the routes will ever be active, yet Angular seems to be ignoring the second route.
Is this mechanic viable at all? or Is there any other technique to achieve the end goal of the first paragraph?.
For completeness' sake I am using @angular/router and @angular/core with version 5.2.8.
Upvotes: 0
Views: 756
Reputation: 21
Yes, you can have multiple Components associated to a single route:
app.component.html
<div class="block">
<div class="columns">
<div class="column is-two-thirds">
<router-outlet></router-outlet>
</div>
<div class="column">
<router-outlet name="aux"></router-outlet>
</div>
</div>
</div>
Routing Config
{
path: 'my-single-url',
children: [
{ path: '', component: ComponentOne },
{ path: '', component: ComponentTwo, outlet: 'aux' }
]
}
Upvotes: 0
Reputation: 60518
You can do something like this:
{ path: '', component: MyService.DoACheck() ? LandingComponent, LocationsComponent },
But that then would not use your guards.
The more common solution, I'm assuming, is the one you don't want:
Define one route with a guard.
In that route guard, determine if the user can access the route, if not, navigate to the other route.
Like this:
export class AuthGuard implements CanActivate {
constructor(private authService: AuthService,
private router: Router) { }
canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): boolean {
return this.checkLoggedIn(state.url);
}
checkLoggedIn(url: string): boolean {
if (this.authService.isLoggedIn()) {
return true;
}
// Retain the attempted URL for redirection
this.authService.redirectUrl = url;
this.router.navigate(['/login']);
return false;
}
}
Upvotes: 1