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

相关内容

热门资讯

攻略讲解!wpk俱乐部是做什么... 您好,攻略讲解!wpk俱乐部是做什么的,德普之星开挂透视教程插件(本然有透视挂)这款游戏可以开挂的,...
1.9分钟了解!wepoker... 1.9分钟了解!wepoker辅助器官方,wepoker开挂破解脚本(最初存在有辅助器)AI 是一款...
解密关于!wpk透视辅助下载,... wpk透视辅助下载AI 游戏攻略黑科技上线本地缓存功能,离线查阅能力开挂。提前下载对应游戏攻略数据包...
信息共享!wepokerplu... 本地部署 AI 黑科技工具迎来新版本,不用上传文件到云端就能完成wepokerplus到底是挂了吗解...
切实教程!wpk辅助器下载,德... wpk辅助器下载AI 游戏攻略黑科技上线本地缓存功能,离线查阅能力开挂。提前下载对应游戏攻略数据包,...
我来教大家!wejoker辅助... wejoker辅助脚本AI 游戏攻略黑科技上线本地缓存功能,离线查阅能力开挂。提前下载对应游戏攻略数...
实测揭晓!!wpk透视辅助软件... 很多人使用云端 AI 时,都担心wpk透视辅助软件、内部资料上传带来隐私风险。这款本地运行的 AI ...
分享实测!微扑克透视脚本,德普... 『标题:当前标题』主打赛后复盘的 AI 游戏攻略黑科技走红,对局总结能力开挂。上传对局回放或者战绩截...
玩家亲测!WPK作弊,WPK开... 『标题:当前标题』主打赛后复盘的 AI 游戏攻略黑科技走红,对局总结能力开挂。上传对局回放或者战绩截...
重要通知!wpk透视辅助方法,... 重要通知!wpk透视辅助方法,wepoker是不是有挂脚本(好像是真的有透视)主打本地运行的 AI ...