What are Route Guards?
Angular’s route guards are interfaces that can tell the router whether or not it should allow navigation to a requested route. They make this decision by looking for a true
or false
the return value from a class that implements the given guard interface.
There are five different types of guards and each of them is called in a particular sequence. The router’s behavior is modified differently depending on which guard is used. The guards are:
There are five different types of guards and each of them is called in a particular sequence. The router’s behavior is modified differently depending on which guard is used. The guards are:
CanActivate
CanActivateChild
CanDeactivate
CanLoad
Resolve
import { Injectable } from '@angular/core'; import { HttpClient } from '@angular/common/http' import { Router } from '@angular/router' @Injectable() export class AuthService { constructor( private http: HttpClient, private _router: Router ) { } loggedIn() { return !!localStorage.getItem('token') } }
CanActivate import { Injectable } from '@angular/core'; import { CanActivate, Router } from '@angular/router'; import { AuthService } from './auth.service'; @Injectable() export class AuthGuard implements CanActivate { constructor(private _authService: AuthService, private _router: Router) { } canActivate(): boolean { if (this._authService.loggedIn()) { console.log('true') return true } else { console.log('false') this._router.navigate(['/login']) return false } } }