Home > OS >  redirect user to home page when user does not have any permission in angular13
redirect user to home page when user does not have any permission in angular13

Time:02-01

I have a home page and menu and I want to redirect user to home page when search URL does not permission for user. Thanks if anyone can help.

CodePudding user response:

Step 1: Create an authentication service First, you must have an authentication service. So you need to create auth.service.ts.

To create a service, do the following:

ng g service auth

Step 2: Create an angular guard

This will create auth.guard.ts which implements CanActivate interface.

Create command:

ng g guard auth

import { Injectable } from '@angular/core';
import { CanActivate, ActivatedRouteSnapshot, RouterStateSnapshot, Router } from '@angular/router';
import { Observable } from 'rxjs';
import { AuthService } from './auth.service';

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

  constructor(private authService: AuthService, private router: Router) {}

  canActivate(
    next: ActivatedRouteSnapshot,
    state: RouterStateSnapshot): Observable<boolean> | Promise<boolean> | boolean {

      if (!this.authService.isLoggedIn()) {
        this.router.navigate(['/login']); // go to login if not authenticated
        return false;
      }
    return true;
  }
}

Step 3: Use the guard inside routes Angular routes has a property called canActivate which accepts an array of guards which will be checked before routing to the specific route.

app-routing.module.ts

import { NgModule } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';
import { HomeComponent } from './home/home.component';
import { LoginComponent } from './login/login.component';
import { AuthGuard } from './auth.guard';

const routes: Routes = [
  { path: '', redirectTo: '/home', pathMatch: 'full' },
  { path: 'login', component: LoginComponent },
  { path: 'home', component: HomeComponent,
    canActivate: [AuthGuard], // visit home only if authenticated
  },
];

@NgModule({
  imports: [RouterModule.forRoot(routes)],
  exports: [RouterModule]
})
export class AppRoutingModule { }
  •  Tags:  
  • Related