0

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?

webblover
  • 1,196
  • 2
  • 12
  • 30

1 Answers1

1

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}     
      ]

  }
];
Pramod Patil
  • 2,704
  • 2
  • 14
  • 20
  • I'm not convinced if it's the right approach because of two reasons. 1, "CanActivate" component of router seems to be dealing with just two user states like "authorized" or "unauthorized" in the application. All examples showing class "AuthGuard" seems to only deal with it. 2, If the number of modules grow from 2 to 50 or more, it would be tedious to inject the "AuthGuard" dependency in all routes configuration in all modules. Is there any other simpler solution? – webblover May 02 '17 at 11:56
  • Additionally, my use case doesn't need **AuthGuard class** because it's not concerned whether it's authorized user request or not. – webblover May 02 '17 at 11:59