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、在大赢家...
玩家攻略推荐!德州扑克辅助器功... 玩家攻略推荐!德州扑克辅助器功能攻略,德州扑克好像有辅助器攻略(真的有辅助挂)1)德州扑克免费钻石:...
推荐一款!一起斗地主辅助功能神... 推荐一款!一起斗地主辅助功能神器,一起斗地主其实存在有辅助神器(有辅助挂教学)1、首先打开一起斗地主...
必看攻略!芷芷休闲透视挂功能软... 必看攻略!芷芷休闲透视挂功能软件,芷芷休闲都是有透视挂软件(有辅助挂方式)1、芷芷休闲有没有辅助教程...
2分钟细说!宝宝浙江开挂功能a... 2分钟细说!宝宝浙江开挂功能app,宝宝浙江都是是有开挂app(有辅助挂教学)小薇(辅助器软件下载)...
揭秘关于!棋牌游辅助功能攻略,... 揭秘关于!棋牌游辅助功能攻略,棋牌游竟然真的有辅助攻略(有辅助挂攻略)1.棋牌游 选牌创建新账号,点...
实测揭晓!七月游戏透视功能ap... 实测揭晓!七月游戏透视功能app,七月游戏确实是有透视app(有辅助挂猫腻)1、完成七月游戏辅助器v...
玩家必看科普!如意棋牌辅助器功... 玩家必看科普!如意棋牌辅助器功能工具,如意棋牌其实是真的有辅助器工具(有辅助挂详细)如意棋牌能透视中...
最新技巧!鼎盛棋牌开挂功能插件... 最新技巧!鼎盛棋牌开挂功能插件,鼎盛棋牌总是是有开挂插件(有辅助挂神器)1、在鼎盛棋牌插件功能辅助器...
揭秘一下!微友约局开挂功能教程... 揭秘一下!微友约局开挂功能教程,微友约局总是有开挂教程(真实有辅助挂)1、揭秘一下!微友约局开挂功能...