2

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.

ali memar
  • 262
  • 2
  • 9
  • have a look at https://angular.io/api/router/CanActivate and https://medium.com/@ryanchenkie_40935/angular-authentication-using-route-guards-bf7a4ca13ae3 – Zerotwelve Feb 01 '22 at 08:27

1 Answers1

4

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 { }
Mahdi Saeidi
  • 176
  • 4