Angular13路由守卫(canActivate)只在第一次页面加载时起作用
创始人
2024-10-22 00:00:07
0

这是因为 Angular 13 路由在第一次加载时会缓存路由信息,而 canActivate 守卫只会在第一次加载页面时检查。如果页面在不同的路由之间切换,canActivate 守卫将不会再次触发。

为了解决这个问题,我们可以使用另一个路由守卫 - canActivateChild。它会在每次子路由加载时都进行检查。以下是示例代码:

import { Injectable } from '@angular/core'; import { CanActivateChild, ActivatedRouteSnapshot, RouterStateSnapshot, UrlTree } from '@angular/router'; import { Observable } from 'rxjs';

@Injectable({ providedIn: 'root' }) export class MyAuthGuard implements CanActivateChild { canActivateChild( next: ActivatedRouteSnapshot, state: RouterStateSnapshot): Observable | Promise | boolean | UrlTree { // 在这里加上你的权限检查逻辑 return true; // 或 false } }

在路由模块中使用 canActivateChild 守卫:

import { NgModule } from '@angular/core'; import { RouterModule, Routes } from '@angular/router'; import { MyAuthGuard } from './my-auth.guard'; import { HomeComponent } from './home.component';

const routes: Routes = [ { path: '', canActivateChild: [MyAuthGuard], children: [ { path: 'home', component: HomeComponent }, // 其他路由配置 ] } ];

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

现在,每次用户在不同的子路由之间切换时,MyAuthGuard 都会在每次子路由加载时都进行检查。

相关内容

热门资讯

近日!hh poker插件下载... 近日!hh poker插件下载,微乐广西麻辣辅助器,推荐脚本(有挂透明挂)-哔哩哔哩hh poker...
脚本推荐!wepoker怎么设... 脚本推荐!wepoker怎么设置盖牌,wepokerplus外g挂(透视)确实有app(哔哩哔哩)1...
出现新变化!竞技联盟透视插件,... 出现新变化!竞技联盟透视插件,微乐贵阳足鸡麻将开挂,详情脚本(真的有挂)-哔哩哔哩1、下载好竞技联盟...
脚本解密!wpk德州局透视,w... 脚本解密!wpk德州局透视,wpk模拟器多开(透视)果然是有器(哔哩哔哩)1、每一步都需要思考,不同...
透视演示!htx矩阵wepok... 透视演示!htx矩阵wepoker辅助,WePoKer钻石一贯真的有教程,八分钟教程(有挂猫腻)1、...
最终!线上德州的辅助器是什么,... 最终!线上德州的辅助器是什么,微乐广西自建房免费黑科技下载,透视透视(有挂猫腻)-哔哩哔哩1、进入游...
透视操作!hhpoker可以控... 透视操作!hhpoker可以控制吗,HHpoker德州竟然真的是有安装,2分钟教程(详细教程)1、操...
围绕透视问题!德州hhpoke... 围绕透视问题!德州hhpoker是真的吗,小程序微乐贵阳捉鸡麻将挂,详情透视(有挂猫腻)-哔哩哔哩所...
透视必备!aapoker透视方... 透视必备!aapoker透视方法,aapoker公共底牌(透视)本来是真的教程(哔哩哔哩)1、很好的...
透视辅助!wejoker开挂,... 透视辅助!wejoker开挂,微乐小程序游戏辅助器脚本官网,分享脚本(有挂规律)-哔哩哔哩透视辅助!...