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

相关内容

热门资讯

方法辅助挂!hhpoker的辅... 方法辅助挂!hhpoker的辅助是真的吗,德普之星辅助工具如何设置,好像存在有挂(证实有挂)暗藏猫腻...
2026版软件!约局吧能不能开... 2026版软件!约局吧能不能开挂,德普之星辅助工具如何打开,竟然存在有挂(有挂技巧)1、玩家可以在德...
现有关情况通报如下!哈糖大菠萝... 现有关情况通报如下!哈糖大菠萝助手,德普之星透视辅助软件下载,真是真的有挂(有挂方法)亲,关键说明,...
黑科技技巧!hhpoker辅助... 黑科技技巧!hhpoker辅助软件下载,智星菠萝可以辅助吗,切实存在有挂(有挂方法)1、下载好智星菠...
据相关数据显示!we poke... 据相关数据显示!we poker游戏下,德普之星怎么开辅助,一贯真的是有挂(确实有挂)1、德普之星怎...
这一问题亟待解决!wejoke... 这一问题亟待解决!wejoker辅助器怎么卖,德普之星透视软件免费入口官网,果然真的是有挂(有人有挂...
2026版攻略!epoker免... 2026版攻略!epoker免费透视脚本,德普辅助软件,果然存在有挂(有挂讲解)1、这是跨平台的德普...
此事备受玩家关注!哈糖大菠萝万... 此事备受玩家关注!哈糖大菠萝万能挂,德普之星辅助器,原来是有挂(有挂教程)1、游戏颠覆性的策略玩法,...
经调查!wepoker透视方法... 经调查!wepoker透视方法,德普之星怎么设置埋牌,真是确实有挂(证实有挂)1、每一步都需要思考,...
有玩家发现!hhpoker智能... 有玩家发现!hhpoker智能辅助插件,德普之星透视辅助,竟然真的是有挂(有人有挂)1、用户打开应用...