i created Two Guards:
- 1st one is preventing to enter website without LogIn:
import {ActivatedRouteSnapshot, CanActivate, Router, RouterStateSnapshot, UrlTree} from '@angular/router';
import {map, Observable} from 'rxjs';
import {LoginService} from "../app/services/login.service";
@Injectable({
providedIn: 'root'
})
export class AuthGuard implements CanActivate {
constructor(private loginService: LoginService, private router: Router) {
}
canActivate(
route: ActivatedRouteSnapshot,
state: RouterStateSnapshot): Observable<boolean | UrlTree> | Promise<boolean | UrlTree> | boolean | UrlTree {
return this.loginService.isUserLoggedIn$.pipe(
map(isLoggedIn => isLoggedIn ? isLoggedIn : this.router.parseUrl('/welcome'))
)
}
}
And the secound one is preventing already logged User to enter loginpage:
import { Injectable } from '@angular/core';
import {ActivatedRouteSnapshot, CanActivate, Router, RouterStateSnapshot, UrlTree} from '@angular/router';
import {map, Observable} from 'rxjs';
import {LoginService} from "../app/services/login.service";
@Injectable({
providedIn: 'root'
})
export class WelcomeGuard implements CanActivate {
constructor(private readonly loginService: LoginService, private readonly router:Router) {
}
canActivate(
route: ActivatedRouteSnapshot,
state: RouterStateSnapshot): Observable<boolean | UrlTree> | Promise<boolean | UrlTree> | boolean | UrlTree {
return this.loginService.isUserLoggedIn$.pipe(map(isLoggedIn => isLoggedIn ? this.router.parseUrl('/'): !isLoggedIn))
}
}
The funny part is, they both are working when there is only one implemented at the same time, but when im adding both of them they are blocking entering websites, but not redirecting. Here is routing:
const routes: Routes = [
{
path: 'main-regulation',
loadChildren: () => import('./modules/main-regulation/main-regulation.module').then(m => m.MainRegulationModule)
},
{
path: '',
canActivate:[AuthGuard],
loadChildren: () => import('./modules/main-page/main-page.module').then(m => m.MainPageModule),
},
{
path: 'user-dashboard',
component: UserDashboardComponent
},
{
path: 'admin-dashboard',
component: AdminDashboardComponent
},
{
path: 'welcome',
loadChildren: () => import('./modules/welcome/welcome.module').then(m => m.WelcomeModule),
canActivate:[WelcomeGuard],
}
];
I tried canLoad, canActivateChild, i tried everything and this redirect i not working. Kind regards