Use Route Guards on the Navigation
First of all, we can accept or decline permission to navigate the URL requested by users by working on the route guard interface. Route guards are using a boolean value concept like if they all return true value then the user can navigate to the requested URL and if anyone returns a false value then the user will be a block to navigate that URL
Different types of route guards:
-
CanActivate:Checks for the component can be accessed by the user or not
-
CanActivateChild:This method checks whether the child component can be accessed or not
-
CanLoad:It can be checked before the load feature module
-
Resolve:It makes sure that data related navigation is available or not so it is pre-fetch the route data.
-
CanDeactivate: It asks for authorization to discard the changes
Route Guard example:
Ā
import { Injectable } from '@angular/core';
import { Router, CanActivate, ActivatedRouteSnapshot, RouterStateSnapshot } from '@angular/router';
export class RouteGuard implements CanActivate {
constructor(private router: Router) { }
canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot) {
// user may login if token exists
if (localStorage.getItem('token')) {
return true;
}
// otherwise redirect to login page
this.router.navigate(['/login'], { queryParams: { returnUrl: state.url } });
return false;
}
}
Ā
Now, apply the same route guard in the route of the RouteModule. Following code, we have defined the route app.module file.
Ā
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { RouteGuard } from './Services/routeGuard';
....
@NgModule({
declarations: [
....
],
imports: [
RouterModule.forRoot([
{ path: '', component: HomeComponent, pathMatch: 'full', canActivate: [RouteGuard] },
{ path: 'myprofile', component: MyProfileComponent, canActivate: [RouteGuard] },
....
]),
....
],
....}) export class AppModule { }
Ā
Generally, user logged-in information like name, email, authentication token, etc will be used by the programmer. we store information in local storage or window session storage.
Here, Windows session storage is more secure than local storage because it is removing user data when the browser gets close and it will prevent any unauthorized users from accessing the userās data.
Use window session storage or local storage to maintain data according to your project requirement but make sure that when the user logged out the data of that user must be cleared.