Protecting Child Routes with canActivate in Angular 4

canActive used for protect also for child routes in angular 4

Create auth.service.ts file

–auth.service.ts

export class AuthService {
    loggedIn = false;

    isAuthenticated(){
        const promise = new Promise(
            (resolve, reject) => {
                setTimeout(() => {
                    resolve(this.loggedIn)
                }, 800);
            }
        )
        return promise;
    }

    login() {
        this.loggedIn = true;
    }

    logout(){
        this.loggedIn = false;
    }
}

Create auth-guard.service.ts file

–auth-guard.service.ts

import { Injectable } from "@angular/core";
import { CanActivate, CanActivateChild, ActivatedRouteSnapshot, RouterStateSnapshot, Router } from "@angular/router";
import { Observable } from "rxjs/Observable";
import { AuthService } from "./auth.service";

@Injectable()
export class AuthGuard implements CanActivate, CanActivateChild {
    constructor(private authService: AuthService, private router: Router) {}

    canActivate(route: ActivatedRouteSnapshot,
                state: RouterStateSnapshot ): Observable | Promise | boolean {
        return this.authService.isAuthenticated()
            .then(
                (authenticated: boolean) => {
                    if(authenticated) {
                        return true;
                    } else {
                        this.router.navigate(['/']);
                    }
                }
            )
    }
    
    canActivateChild(route: ActivatedRouteSnapshot,
        state: RouterStateSnapshot ): Observable | Promise | boolean {
            return this.canActivate(route, state);
    }
}

Add into routing code.

const appRoutes: Routes = [
    { path: '', redirectTo:'/home', pathMatch:'full'},
    { path: 'home', component: HomeComponent},
    { path: 'users', component: UsersComponent, children: [
      { path: ':id/:name', component: UserComponent},
    ]},
    { path: 'servers', canActivateChild:[AuthGuard], component: ServersComponent, children: [
      { path: ':id', component: ServerComponent},
      { path: ':id/edit', component: EditServerComponent},
    ]},
    { path: 'error-404', component: Page404Component},
    { path: '**', redirectTo: '/error-404'}
  ]

Now you can see, you not able to go in pages of servers page.

Leave a Reply

Your email address will not be published. Required fields are marked *