当用户在 angular13 中没有任何权限时将用户重定向到主页

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

我有一个主页和菜单,我想在搜索 URL 没有用户权限时将用户重定向到主页。 如果有人能帮忙,谢谢。

第 1 步:创建身份验证服务 首先,您必须拥有身份验证服务。所以你需要创建auth.service.ts.

要创建服务,请执行以下操作:

ng g service auth

第 2 步:创建一个 angular 守卫

这将创建实现 CanActivate 接口的 auth.guard.ts

创建命令:

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;
  }
}

第 3 步:在路由内使用守卫 Angular 路由有一个名为 canActivate 的 属性,它接受一组守卫,这些守卫将在路由到特定路由之前进行检查。

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 { }