I'm writing a mock e-commerce app which has the following structure:
const routes: Routes = [
{
path: 'signup',
component: SignUpPage,
},
{
path: 'signin',
component: SignInPage,
},
];
const routes: Routes = [
{
path: 'admin',
component: RootPage,
children: [
// ...
],
},
];
const routes: Routes = [
{
path: 'customer',
component: RootPage,
children: [
{ path: 'catalog/:categoryId', component: CatalogPage },
{ path: 'checkout', component: CheckOutPage },
{ path: 'thankyou', component: ThankYouPage },
],
},
];
const routes: Routes = [
{ path: '**', component: NotFoundPage },
];
The basic workflow is supposed to be as follows:
/
./signin
./admin
.
admin-router.module.ts
redirects them to some sub-path of /admin
./customer
.
customer-router.module.ts
redirects them to /customer/catalog/<default category ID>
./customer/checkout
./customer/thankyou
.What I'm not sure about is how to accomplish the redirection following a successful log-in. Obviously it has to be done in two stages: first to some common path such as /
and then either to /customer
or to /admin
depending on the user's role. The second stage probably needs to be handled by app-routing.module.ts
, perhaps using a guard, but I'm not sure exactly how to do it.
The problem can be summarized as follows:
What I need is a way (preferably declarative) to redirect the application from /
to one of the following paths depending on its state:
State | Path |
---|---|
Logged out | /auth |
Logged in as a customer | /customer |
Logged in as an admin | /admin |
What I ended up doing is this:
// app-routing.module.ts
const routes: Routes = [
{
path: '',
canActivate: [AuthorizationGuard],
children: [],
},
{ path: '**', component: NotFoundPage },
];
// authorization.guard.ts
@Injectable({
providedIn: 'root',
})
export class AuthorizationGuard implements CanActivate {
constructor(private router: Router, private authService: AuthService) {}
canActivate(
route: ActivatedRouteSnapshot,
state: RouterStateSnapshot
): UrlTree {
const user = this.authService.getLoggedInUser();
return (
(user?.role === 'admin' && this.router.parseUrl('/admin')) ||
(user?.role === 'customer' && this.router.parseUrl('/customer')) ||
this.router.parseUrl('/auth')
);
}
}