How to restrict your logged In page in angular (authentication guard)

 You can set authentication guard to restrict users which are not loggedin.

1) Service of auth guard  

import { Injectable } from '@angular/core';
import { Router, CanActivate, ActivatedRouteSnapshot,RouterStateSnapshot, UrlTree } from '@angular/router';
import {CookieService} from 'ngx-cookie-service';


@Injectable({
providedIn: 'root'
})
export class AuthGuardService implements CanActivate {

constructor(private _router:Router,private _cookieService: CookieService) { }
userid="";
canActivate(route: ActivatedRouteSnapshot,
state: RouterStateSnapshot): boolean|UrlTree {

this.userid = this._cookieService.get('userid')
if(this.userid=="") {
alert('You are not allowed to view this page. You are redirected to login Page');

this._router.navigate(["login"],{ queryParams: { retUrl: route.url} });
return false;

//var urlTree = this.router.createUrlTree(['login']);
//return urlTree;
}

return true;
}
} 2) Add service refernce to Provider in app.module
import { AuthGuardService } from './services/auth-guard.service';
providers: [{ provide: RouteReuseStrategy, useClass: IonicRouteStrategy },CookieService,AuthGuardService], 3) Now finally add this guard to your rout to restrict users.
import { NgModule } from '@angular/core';
import { RouterModule, Routes } from '@angular/router';

import{HomeComponent} from './home/home.component'

import { AuthGuardService } from '../services/auth-guard.service';


const routes: Routes = [
{ path: 'home', component: HomeComponent, canActivate : [AuthGuardService] }
];


@NgModule({
imports: [RouterModule.forChild(routes)],
exports: [RouterModule]
})
export class PublicRoutingModule { }


Comments

Popular posts from this blog

how to save images with angular nodejs

How to add splash screen and app icon with ionic capacitor angular android app

How to export data to excel sheet with colors and style in angular.