The default Angular router allows navigation to and from any route unconditionally. This is not always the desired behavior.
In a scenario where a user may conditionally be allowed to navigate to or from a route, a Route Guard may be used to restrict this behavior.
If your scenario fits one of the following, consider using a Route Guard,
Route Guards work by returning a boolean value to control the behavior of router navigation. If true is returned, the router will continue with navigation to the target component. If false is returned, the router will deny navigation to the target component.
The router supports multiple guard interfaces:
These interfaces can be implemented in your guard to grant or remove access to certain processes of the navigation.
Route Guards allow synchronous and asynchronous operations to conditionally control navigation.
A synchronous route guard returns a boolean, such as by computing an immediate result, in order to conditionally control navigation.
import { Injectable } from '@angular/core';
import { CanActivate } from '@angular/router';
@Injectable()
export class SynchronousGuard implements CanActivate {
canActivate() {
console.log('SynchronousGuard#canActivate called');
return true;
}
}
For more complex behavior, a route guard can asynchronously block navigation. An asynchronous route guard can return an Observable or Promise.
This is useful for situations like waiting for user input to answer a question, waiting to successfully save changes to the server, or waiting to receive data fetched from a remote server.
import { Injectable } from '@angular/core';
import { CanActivate, Router, ActivatedRouteSnapshot, RouterStateSnapshot } from '@angular/router';
import { Observable } from 'rxjs/Rx';
import { MockAuthenticationService } from './authentication/authentication.service';
@Injectable()
export class AsynchronousGuard implements CanActivate {
constructor(private router: Router, private auth: MockAuthenticationService) {}
canActivate(route:ActivatedRouteSnapshot, state:RouterStateSnapshot):Observable<boolean>|boolean {
this.auth.subscribe((authenticated) => {
if (authenticated) {
return true;
}
this.router.navigateByUrl('/login');
return false;
});
}
}