Angular路由器.navigate在canActivate()中不适用于子路由
创始人
2024-10-28 02:32:57
0

这是因为当使用navigate方法时,路由守卫会阻止导航到未激活的子路由。为了解决这个问题,我们需要使用路由器的navigateByUrl方法来导航到子路由。

以下是示例代码:

import { Router, ActivatedRoute } from '@angular/router';
import { Injectable } from '@angular/core';
import { CanActivate } from '@angular/router';

@Injectable()
export class AuthGuard implements CanActivate {

  constructor(private router: Router, private route: ActivatedRoute) {}

  canActivate() {
    if (isAuthenticated()) {
      return true;
    } else {
      // Navigate to login page with the current URL as a query string parameter
      this.router.navigateByUrl('/login?returnUrl=' + this.route.snapshot.url.join('/'));
      return false;
    }
  }
}

在这个示例中,我们使用了navigateByUrl方法来导航到/login子路由,同时将当前URL作为查询字符串参数一起传递。这样,用户在成功登录后将返回之前的URL。

我们需要确保在定义路由时将子路由的定义放在父路由的后面,以确保子路由成功地激活。例如:

const appRoutes: Routes = [
  { path: '', component: HomeComponent },
  { path: 'login', component: LoginComponent },
  { path: 'dashboard', component: DashboardComponent, canActivate: [AuthGuard], children: [
    { path: 'profile', component: ProfileComponent }
  ]},
  { path: '**', component: PageNotFoundComponent }
];

@NgModule({
  imports: [
    RouterModule.forRoot(appRoutes)
  ]
})
export class AppRoutingModule { }

在这个例子中,子路由/profile是由父路由/dashboard激活的。

相关内容

热门资讯

六分钟讲义!aapoker脚本... 六分钟讲义!aapoker脚本怎么用(透视)真是是真的有辅助工具(哔哩哔哩)1、aapoker脚本怎...
6分钟学习!pokemmo手机... 6分钟学习!pokemmo手机脚本辅助器(透视)好像真的有辅助安装(哔哩哔哩)1、下载好pokemm...
四分钟练习!wepoker免费... 四分钟练习!wepoker免费辅助器(透视)一贯是有辅助辅助(哔哩哔哩)1、游戏颠覆性的策略玩法,独...
第四分钟诀窍!智星德州插件最新... 第四分钟诀窍!智星德州插件最新版本更新内容详解(透视)竟然真的有辅助脚本(哔哩哔哩)1、玩家可以在智...
第三分钟经验!佛手在线大菠萝技... 第三分钟经验!佛手在线大菠萝技巧(透视)一贯有辅助教程(哔哩哔哩)1、不需要AI权限,帮助你快速的进...
5分钟法门!有没有人wepok... 5分钟法门!有没有人wepoker(透视)好像是有辅助脚本(哔哩哔哩)1、完成有没有人wepoker...
六分钟操作!wepoker看底... 六分钟操作!wepoker看底牌(透视)都是有辅助辅助(哔哩哔哩)1、游戏颠覆性的策略玩法,独创攻略...
第6分钟手筋!sohoo竞技联... 第6分钟手筋!sohoo竞技联盟辅助器(透视)一直真的有辅助工具(哔哩哔哩)小薇(辅助器软件下载)致...
一分钟项目!wepoker有用... 一分钟项目!wepoker有用吗(透视)确实是真的有辅助安装(哔哩哔哩)1、下载好wepoker有用...
第1分钟妙招!wepoker挂... 第1分钟妙招!wepoker挂(透视)确实真的有辅助神器(哔哩哔哩)进入游戏-大厅左侧-新手福利-激...