Search code examples
angularangular-guards

Angular 6 How to implement canActivateChild


I'm new to Angular auth guard. I have successfully integrated auth guard so that logged in users can access the private pages. For this, I used CanActivate. Now, my intention is to use another type of guard which prevent the logged in users to access some of the private pages. From https://www.concretepage.com/angular-2/angular-2-4-route-guards-canactivate-and-canactivatechild-example, I came to know that I can use canActivateChild to achieve the similar result.

In app-routing.module.ts file I used the below:

const routes: Routes = [ ...
{ path: 'myaccount', loadChildren: '../module/myaccount/myaccount.module#MyAccountModule',canActivate: [AuthGuard] },...];

Under the myaccount component, I have several other child component.

In myaccount-routing.module.ts, I wrote this:

const routes: Routes = [
...
{ path: 'abc', component: AbcComponent,
    children: [
    { path: 'xyz', component: XyzComponent, canActivateChild: [ AuthGuard ] },
... ]
   }
];

In the abc component under myaccount I wrote the following within the abc-routing.module.ts:

const routes: Routes = [
...
{ path: 'xyz', component: XyzComponent, canActivateChild: [ AuthGuard ]},
...
];

This is my auth.guard.ts:

import { Injectable } from '@angular/core';
import { Router, CanActivate, ActivatedRouteSnapshot, RouterStateSnapshot, CanActivateChild} from '@angular/router';
import { CommonService } from './../services/common.service';

@Injectable()
export class AuthGuard implements CanActivate {

  private userData:any={};

    constructor(
        private router: Router,  
        private commService : CommonService
    ) { }

    canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot) {
    ...
    }
    canActivateChild(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): any {
    console.log("fired!);
    return true;
    }
}

When I go to the xyz page from browser say myaccount/abc/xyz, it should fire the browser console however, I can't see any text in browser console. There is no error in the CLI too. I refreshed the xyz page however, no luck. No text in the browser console. Any idea?


Solution

  • Where are you providing AuthGuard?, from the example its not provided at root. You can change that to @Injectable({providedIn:'root'})

    EDIT

    Take a look at this stackblitz, it looks like the canActivateChild is triggered when it has a parent canActivate. If you need to perform a validation on a specific page you should add another canActivate on the page you wish to secure