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激活的。

相关内容

热门资讯

盘点一款!闲逸游戏辅助软件下载... 盘点一款!闲逸游戏辅助软件下载,博雅棋牌辅助器,详细方法(有挂秘诀)1、下载好闲逸游戏辅助软件下载正...
一直以来!agpoker辅助,... 一直以来!agpoker辅助,德普之星辅助工具如何设置,一直是有挂(有挂神器)1.德普之星辅助工具如...
玩家科普!wepoker辅助,... 玩家科普!wepoker辅助,宝宝游戏辅助,详细脚本(有挂功能)宝宝游戏辅助透视方法中分为三种模型:...
2026版教程!wpk作弊是真... 2026版教程!wpk作弊是真的吗,智星德州辅助译码插件靠谱吗,原来真的是有挂(有挂详情)智星德州辅...
必看攻略!川南休闲辅助,微信老... 必看攻略!川南休闲辅助,微信老友广东辅助,详细器(详细教程)微信老友广东辅助破解侠是真的助透视。每个...
今天下午!wepoker免费透... 今天下午!wepoker免费透视脚本,德普之星透视辅助软件是真的吗,真是是真的有挂(今日头条)德普之...
实测教程!微信小程序外辅助工具... 实测教程!微信小程序外辅助工具,网易亲友圈辅助,详细工具(有挂功能)1、这是跨平台的微信小程序外辅助...
现场直击!wepoker辅助器... 现场直击!wepoker辅助器如何使用,德扑之星透视,好像是真的有挂(有挂辅助)1、打开软件启动之后...
玩家必看科普!微乐小程序免费黑... 玩家必看科普!微乐小程序免费黑科技下载,欢乐茶馆挂,详细软件(了解有挂)小薇(辅助器软件下载)致您一...
据文件显示!wepoker透视... 据文件显示!wepoker透视app下载,德扑之星私人局透视,竟然真的有挂(有挂助手)1、点击下载安...