What is RouteGuard

 

AuthGuard or RouteGuard is the interface that a class can implement to be a guard deciding if a route can be activated. If all guards return true, navigation continues. If any guard returns false, navigation is cancelled. 

There are many scenarios when you want to call API to decide whether to allow navigate or not , below example demonstrates how to call API from canActivate.

 

import { Injectable } from '@angular/core';
import { ActivatedRouteSnapshot, CanActivate, Router, RouterStateSnapshot } from '@angular/router';
import { UserService } from './user.service';


@Injectable({
    providedIn: 'root',
})
export class AuthGuard implements CanActivate {
    constructor(private userService: UserService) { }
   
    canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): Promise<boolean> {
           
        return new Promise((resolve, reject) => {
            
            this.userService.CheckAccess().subscribe((permission) => {
                if(permission){
                        resolve(true);
                }else{
                    reject(false)
                }
                                 
            });
            
        });
    }
}