在 angular16 中守卫使用方式进行了更新,route 守卫被弃用(取消了CanActivate的使用),新增了功能性守卫(CanActivateFn),支持 inject 注入,官网提供了一个新的类型
export declare type CanDeactivateFn<T> = (component: T, currentRoute: ActivatedRouteSnapshot, currentState: RouterStateSnapshot, nextState: RouterStateSnapshot) => Observable<boolean | UrlTree> | Promise<boolean | UrlTree> | boolean | UrlTree;
1.使用ng g g /guard/xxxx 命令生成guard文件
import {inject} from '@angular/core'; import { CanDeactivateFn, Router, } from '@angular/router'; export const PermissionsGuard: CanDeactivateFn<any> = () => { const router = inject(Router) //注入需要使用的服务 if (router.url === '/business-module') { console.log("无权限访问,请重新登录"); router.navigate(['/login']); return false } else { return true } }
2.在路由文件中,使用方式与angular 其他版本无差别,无需关注
const routes: Routes = [ { path: 'business-module', component: PermissionsComponent, canActivate: [PermissionsGuard] //使用方式 }, ];
标签:CanDeactivateFn,const,16,守卫,inject,router,angular,路由 From: https://www.cnblogs.com/liyfya/p/17986313