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、公共底牌简单,透视插件操作,插件...
一分钟揭秘!pokemmo脚本... 一分钟揭秘!pokemmo脚本手机版,wepoker开脚本视频,原来是真的有挂(存在有挂)1、下载好...
玩家必备攻略!wepoker插... 您好,这款游戏可以开挂的,确实是有挂的,需要了解加去威信【136704302】很多玩家在这款游戏中打...
分享认知!wepoker轻量版... 分享认知!wepoker轻量版有透视吗,德普之星有透视辅助吗,确实真的有挂(真的有挂)1、透视辅助软...
六分钟了解!德扑圈透视,wep... 六分钟了解!德扑圈透视,wepoker辅助器安装包定制,都是是真的有挂(有挂细节)一、wepoker...
大家学习交流!wepoker插... 大家学习交流!wepoker插件辅助,竞技联盟破解版最新版,原来存在有挂(有挂攻略)1、玩家可以在线...
技术分享!hhpoker德州机... 技术分享!hhpoker德州机器人,aapoker辅助怎么用,总是有挂(有挂攻略)1、每一步都需要思...
一分钟了解!竞技联盟透视,hh... 一分钟了解!竞技联盟透视,hhpoker怎么开透视,好像存在有挂(有挂细节)一、游戏安装教程牌型概率...
玩家必备教程!sohoo po... 玩家必备教程!sohoo poker辅助,hhpoker作弊码怎么用,确实真的是有挂(有挂详情)一、...
热点推荐!哈糖大菠萝攻略,红龙... 热点推荐!哈糖大菠萝攻略,红龙poker作弊指令,果然真的有挂(有挂存在)1、免费脚本咨询教程、免费...