We can check (restrict/allow) an access to a module in Angular RouterModule using Guards, implementing an canActivate()
method. The method can use a business logic to make some checks, lets call it checkAccess()
method. And return a boolean observable.
Imagine, a user visits a module, lets call it Private Page Module
, which is protected by a guard (lets call it CheckAccessGuard
) and in the canActivate()
which returns an observable of a service variable (lets call it haveAccess
. If canActivate()
emits a true
value - then the user gets access to the Private Page Module
. If false
is emitted - let's redirect user to some 403 Access Denied Page
.
On the Private Page Module
, lets add a button, which sets haveAccess
variable to false
. So the next emission by the canActivate()
should return false
and the user should be redirected.
User click on the button - and nothing happens.
Because the user is already on the Private Page Module
. And the guard was already checked.
But I would like to redirect the user to the 403 Access Denied Page
, by executing the guard logic again. And without adding extra code on the Private Page Module
. (So the business logic can be added only in the guard, because the G
guard should check the access). But the guard checks the access only before accessing the page and does not check the access, when the user already is on the page.
I will post some code snippets as an example:
Routes configuration:
const routes: Routes = [
{
path: 'private-area',
loadChildren: () =>
import('./pages/private-page.module').then((m) => m.PrivatePageModule),
canActivate: [CheckAccessGuard],
}
]
CheckAccessGuard:
...
constructor(private checkAccessService: CheckAccessService) {}
canActivate(): Observable<boolean> {
return of(this.checkAccess())
}
checkAccess(): boolean {
return this.checkAccessService.haveAccess;
}
...
CheckAccessService:
export class CheckAccessService {
public haveAccess = true;
}
PrivatePageModule default component:
(.html)
<button (click)="checkAccessService = false">
(.ts)
constructor(public checkAccessService: CheckAccessService) {}