@@ -2,6 +2,7 @@ import { NgModule } from '@angular/core';
|
|
2 |
import { RouterModule, Routes } from '@angular/router';
|
3 |
|
4 |
import { HomeComponent } from './home/home.component';
|
|
|
5 |
|
6 |
const routes: Routes = [
|
7 |
{
|
@@ -19,7 +20,8 @@ const routes: Routes = [
|
|
19 |
},
|
20 |
{
|
21 |
path: 'admin',
|
22 |
-
loadChildren: () => import('./admin/admin.module').then(m => m.AdminModule)
|
|
|
23 |
}
|
24 |
];
|
25 |
|
2 |
import { RouterModule, Routes } from '@angular/router';
|
3 |
|
4 |
import { HomeComponent } from './home/home.component';
|
5 |
+
import { authGuard } from './shared/auth.guard';
|
6 |
|
7 |
const routes: Routes = [
|
8 |
{
|
20 |
},
|
21 |
{
|
22 |
path: 'admin',
|
23 |
+
loadChildren: () => import('./admin/admin.module').then(m => m.AdminModule),
|
24 |
+
canActivate: [authGuard]
|
25 |
}
|
26 |
];
|
27 |
|
@@ -0,0 +1,35 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import { inject } from '@angular/core';
|
2 |
+
import { CanActivateFn, Router } from '@angular/router';
|
3 |
+
import { map, take } from 'rxjs';
|
4 |
+
|
5 |
+
import { AuthService } from './auth.service';
|
6 |
+
|
7 |
+
export const authGuard: CanActivateFn = () => {
|
8 |
+
const authService = inject(AuthService);
|
9 |
+
const router = inject(Router);
|
10 |
+
|
11 |
+
if (authService.isAuthenticated) {
|
12 |
+
return true;
|
13 |
+
} else {
|
14 |
+
window.alert('Not logged in!');
|
15 |
+
return router.parseUrl('/home');
|
16 |
+
}
|
17 |
+
};
|
18 |
+
|
19 |
+
// Alternative Lösung mit Observable
|
20 |
+
export const authGuardAlternative: CanActivateFn = () => {
|
21 |
+
const authService = inject(AuthService);
|
22 |
+
const router = inject(Router);
|
23 |
+
|
24 |
+
return authService.isAuthenticated$.pipe(
|
25 |
+
take(1),
|
26 |
+
map(isAuthenticated => {
|
27 |
+
if (isAuthenticated) {
|
28 |
+
return true;
|
29 |
+
} else {
|
30 |
+
window.alert('Not logged in!');
|
31 |
+
return router.parseUrl('/home');
|
32 |
+
}
|
33 |
+
})
|
34 |
+
);
|
35 |
+
};
|