Skip to content

Instantly share code, notes, and snippets.

@killerchip
Last active July 29, 2018 07:55
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save killerchip/8faaf0d51208b5f2e08734343a209c23 to your computer and use it in GitHub Desktop.
Save killerchip/8faaf0d51208b5f2e08734343a209c23 to your computer and use it in GitHub Desktop.
Angular cheatsheet - Route guards... how to prevent accesss to routes

Route Guards

Route guards are services that implement logic to allow or not fulfilling a route.

generate a guard

You can generate a guard with angular-cli:

> ng generate guard Auth

it will generate the following service:

import { Injectable } from '@angular/core';
import { CanActivate, ActivatedRouteSnapshot, RouterStateSnapshot } from '@angular/router';
import { Observable } from 'rxjs/Observable';

@Injectable()
export class AuthGuard implements CanActivate {
  canActivate(
    next: ActivatedRouteSnapshot,
    state: RouterStateSnapshot): Observable<boolean> | Promise<boolean> | boolean {
    return true
  }
}

implement the decision logig

An example where the guard checks if the user is logged in.

auth.guard.ts:

export class AuthGuard implements CanActivate {

  constructor(
    private logginService: LogginService
  ){}

  canActivate(
    next: ActivatedRouteSnapshot,
    state: RouterStateSnapshot): Observable<boolean> | Promise<boolean> | boolean {
    return this.logginService.isLoggedIn(); //here we indicate if we allow or not the page to be entered
  }

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment