Angular Js

How To Use CanActivate and CanActivateChild Route Guards with Angular?

How To Use CanActivate and CanActivateChild Route Guards with Angular?

CanActivate and CanActivateChild Route Guards with Angular?

This Article helps you to Understand, How To Use CanActivate and CanActivateChild Route Guards with Angular?


There are the 4 types of routing guards available:
CanActivate: Controls if a route can be activated.
CanActivateChild: Controls if children of a route can be activated.
CanLoad: Controls if a route can even be loaded. This becomes useful for feature modules that are lazy-loaded. They won’t even load if the guard returns false.
CanDeactivate: Controls if the user can leave a route. Note that this guard doesn’t prevent the user from closing the browser tab or navigating to a different address. It only prevents actions from within the application itself.


Define Simple Auth Service


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


Using the CanActivate and CanActivateChild Route Guard
Route guards are most often implemented as classes that implement the needed route guard interface.
Let’s consider an example with a CanActivate route guard where we ask an auth service if the user is authenticated:


auth-guard.service.ts

import {
  CanActivate,
  ActivatedRouteSnapshot,
  RouterStateSnapshot,
  Router,
  CanActivateChild
} from '@angular/router';
import { Observable } from 'rxjs/Observable';
import { Injectable } from '@angular/core';
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<boolean> | Promise<boolean> | boolean {

    return this.authService.isAuthenticated()
      .then(
        (authenticated: boolean) => {
          if (authenticated) {
            return true;
          } else {
            this.router.navigate(['/']);
          }
        }
      );
  }

  canActivateChild(
route: ActivatedRouteSnapshot,
      state: RouterStateSnapshot): Observable<boolean> | Promise<boolean> | boolean {
    return this.canActivate(route, state);
  }
}

Take note of how we declared a canActivate method to implement the CanActivate interface. In situations where you might need information about the current route, the method has optional access to the ActivatedRouteSnapshot and the RouterStateSnapshot.

The canActivate returns a boolean depending on if the user is authenticated or not, but it could have also returned an observable or a promise that resolve to a boolean.



User Route Guard
In order to use them, route guards should be provided like services.so we have to register our Guard in app.module.ts


app.module.ts

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { FormsModule } from '@angular/forms';

import { AuthService } from './auth.service';
import { AuthGuard } from './auth-guard.service';
import { ErrorPageComponent } from './error-page/error-page.component';

@NgModule({
  declarations: [
    AppComponent,
    PageNotFoundComponent,
    ErrorPageComponent
  ],
  imports: [
    BrowserModule,
    FormsModule,
    AppRoutingModule
  ],
  providers: AuthService, AuthGuard],
  bootstrap: [AppComponent]
})
export class AppModule { }


Define Which Route should be Protected by these Guards
And then lastly, you’ll want to add the guard as part of your routing configuration.

app-routing.module.ts

import
{ NgModule } from "@angular/core";
import { Routes, RouterModule } from "@angular/router";
import { PageNotFoundComponent } from "./page-not-found/page-not-found.component";
import { AuthGuard } from "./auth-guard.service";
import { ErrorPageComponent } from "./error-page/error-page.component";
import { DashboardComponent } from "./home/dashboard.component";

import { ServersComponent } from "./servers/servers.component";
import { ServerComponent } from "./servers/server/server.component";
import { EditServerComponent } from "./servers/edit-server/edit-server.component";

const appRoutes: Routes = [   
{ path: '', component: HomeComponent },
  { path: 'dashboard',
    component: DashboardComponent,
    canActivate: [AuthGuard]
  },
{
    path: "servers"
    canActivateChild: [AuthGuard],
    component: ServersComponent,
    children: [
      {
        path: ":id",
        component: ServerComponent,
        resolve: { server: ServerResolver }
      },    
    ]
  },
];

@NgModule({
  imports: [RouterModule.forRoot(appRoutes, { useHash: true })],
  exports: [RouterModule]
})
export class AppRoutingModule {}



Now only users that are authenticated can activate the /dashboard route.
Notice how we provide an array of guards in the route definition. This means that we could specify multiple guards for a single route, and they’ll be evaluated in the order in which they are specified.






Related Post

About Us

Community of IT Professionals

A Complete IT knowledgebase for any kind of Software Language, Development, Programming, Coding, Designing, Networking, Hardware and Digital Marketing.

Instagram