I have the following routes configuration in app.module.ts,
{
path: 'login',
component: loginComponent,
canActivate: [loggerService]
}, {
path: '',
component: AppComponent,
canActivate: [loggerService]
}, {
path: '/home',
redirectTo: ''
}, {
path: '/blog',
component: BlogComponent,
canActivate: [loggerService]
}
When any of the routes is called, I want a method to run. For example, to log the access or pre-request some data. Is there any default user-defined or in-built method that can be used to achieve this?
Yes.There is a way to have Auth guard implementation.Below is the eg:
import { Injectable } from '@angular/core';
import { CanActivate, ActivatedRouteSnapshot, RouterStateSnapshot, CanActivateChild, Router } from '@angular/router';
@Injectable()
export class AuthGuard implements CanActivate, CanActivateChild {
constructor(private router: Router) {
}
canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): boolean {
if (condition)) {
return true;
}
this.router.navigate(['/unauthorized']);
return false;
}
canActivateChild(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): boolean {
return this.canActivate(route, state);
}
}
In you routes:
import { Routes, RouterModule } from '@angular/router';
import { AuthGuard } from 'Your Location/auth-guard.service';
const ROUTES: Routes = [
{
path: '',
canActivateChild: [AuthGuard],
children: [
{path: '', component: CardbrandComponent}
]
}
];