Taobin-Recipe-Manager/client/src/app/app-routing.module.ts

82 lines
1.9 KiB
TypeScript
Raw Normal View History

2023-09-18 08:50:13 +07:00
import { NgModule, inject } from '@angular/core';
import { CanActivateFn, Router, RouterModule, Routes } from '@angular/router';
import { UserService } from './core/services/user.service';
import { Subject, finalize, lastValueFrom, map, takeUntil } from 'rxjs';
2023-09-18 08:50:13 +07:00
const authGuard: CanActivateFn = () => {
const userService: UserService = inject(UserService);
const router: Router = inject(Router);
2023-09-18 08:50:13 +07:00
return userService.isAuthenticated.pipe(
map((isAuth) => {
if (isAuth) {
return true;
}
return router.parseUrl('/login');
})
2023-09-18 08:50:13 +07:00
);
};
const loginGuard: CanActivateFn = () => {
const userService: UserService = inject(UserService);
const router: Router = inject(Router);
return lastValueFrom(userService.getCurrentUser())
.then(({ user }) => {
if (user) {
return router.parseUrl('/dashboard');
2023-09-18 08:50:13 +07:00
}
return true;
2023-09-18 08:50:13 +07:00
})
.catch(() => {
return true;
});
2023-09-18 08:50:13 +07:00
};
2023-09-14 14:52:04 +07:00
const routes: Routes = [
2023-09-18 08:50:13 +07:00
{
path: 'login',
loadComponent: () =>
import('./core/auth/auth.component').then((m) => m.AuthComponent),
canActivate: [loginGuard],
},
{
path: 'callback',
2023-09-18 08:50:13 +07:00
loadComponent: () =>
import('./core/callback/callback.component').then(
(m) => m.CallbackComponent
),
2023-09-18 08:50:13 +07:00
},
2023-09-14 14:52:04 +07:00
{
path: '',
loadComponent: () =>
2023-09-18 08:50:13 +07:00
import('./core/layout/layout.component').then((m) => m.LayoutComponent),
children: [
{
path: '',
pathMatch: 'full',
redirectTo: 'dashboard',
},
{
path: 'dashboard',
loadComponent: () =>
import('./features/dashboard/dashboard.component').then(
(m) => m.DashboardComponent
),
canActivate: [authGuard],
},
],
2023-09-14 14:52:04 +07:00
},
{
path: '**',
pathMatch: 'full',
redirectTo: 'dashboard',
},
2023-09-14 14:52:04 +07:00
];
@NgModule({
imports: [RouterModule.forRoot(routes)],
exports: [RouterModule],
})
export class AppRoutingModule {}