Example of CanLoad and CanActivate for login authentication

From Basef
Jump to: navigation, search

CanLoad can be used to restrict access to assets, while CanActivate is used to restrict access to routes:

loggedin.guard.ts

import { CanLoad, Route, CanActivate, ActivatedRouteSnapshot, RouterStateSnapshot, Router } from '@angular/router';
import { Injectable } from '@angular/core';
import { LoginService } from './login.service';
 
@Injectable()
export class LoggedInGuard implements CanLoad, CanActivate {
 
  constructor(private loginService: LoginService, private route: Router) {
  }
 
  checkAuthentication(path: string): boolean {
    const isLoggedIn = this.loginService.isLoggedIn();
 
    if(!isLoggedIn) {
      this.route.navigate(['/login']);
    }
 
    return isLoggedIn;
  }
 
  canLoad(route: Route): boolean {
    return this.checkAuthentication(route.path);
  }
 
  canActivate(activatedRouter: ActivatedRouteSnapshot, routerState: RouterStateSnapshot): boolean {
    return this.checkAuthentication(activatedRouter.routeConfig.path);
  }
}


In your module:

import { LoggedInGuard } from "./login/loggedin.guard";
 
@NgModule({
  ...
  providers: [
    ...
    LoggedInGuard,
    ...
  ]
  ...
})

In your router:

import { NgModule } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';
import { LoginComponent } from './login/login.component';
import { ReportsComponent } from './reports/reports.component';
import { LoggedInGuard } from "./login/loggedin.guard";
 
const ROUTES: Routes = [
  ...
  {
    path: 'path-you-want-to-restrict',
    component: MyComponent,
    canActivate: [LoggedInGuard]
  },
  ...
];
 
@NgModule({
  imports: [RouterModule.forRoot(ROUTES)],
  exports: [RouterModule]
})
export class AppRoutingModule { }