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

相关内容

热门资讯

9分钟辅助!aapoker如何... 9分钟辅助!aapoker如何设置胜率,aapoker破解侠是真的吗,指引教程(有挂教学)1、aap...
1分钟辅助!wejoker黑侠... 1分钟辅助!wejoker黑侠辅助器,wepoker软件安装包,讲义教程(新版有挂)1、全新机制【w...
六分钟辅助!来玩德州破解器,s... 六分钟辅助!来玩德州破解器,sohoo poker辅助,步骤教程(有挂方法)1、操作简单,无需来玩德...
4分钟辅助!德州圈脚本,wep... 4分钟辅助!德州圈脚本,wepoker透视功能下载,学习教程(竟然有挂)1、操作简单,无需wepok...
6分钟辅助!wepoker插件... 6分钟辅助!wepoker插件程序激活码,wepoker透视脚本免费app,窍门教程(有挂解密)1、...
五分钟辅助!aapoker能控... 五分钟辅助!aapoker能控制牌吗,hhpoker透视脚本,学习教程(有挂方针)1、玩家可以在aa...
三分钟辅助!智星菠萝可以辅助吗... 三分钟辅助!智星菠萝可以辅助吗,德州真人透视脚本,绝活儿教程(有挂方法)三分钟辅助!智星菠萝可以辅助...
第8分钟辅助!wepoker有... 第8分钟辅助!wepoker有没有辅助,hhpoker必备开挂,法门教程(真实有挂)1、超多福利:超...
4分钟辅助!wejoker开挂... 4分钟辅助!wejoker开挂,sohoo poker辅助器,模板教程(有挂技巧)1、首先打开soh...
第七分钟辅助!wpk模拟器,w... 第七分钟辅助!wpk模拟器,wpk透视辅助靠谱吗,妙计教程(有挂细节)在进入wpk透视辅助靠谱吗软件...