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真的假的,德普之星辅助工具如何设置,好像真的是有挂(真是有挂)一、德普之...
推荐一款!werplan怎么作... 推荐一款!werplan怎么作弊,cloudpoker外挂,总是是有挂(有挂教学)推荐一款!werp...
今天上午!大菠萝789辅助器下... 今天上午!大菠萝789辅助器下载,德扑圈透视,一贯确实有挂(真实有挂)1、打开软件启动之后找到中间准...
重大通报!wepoker如何设... 重大通报!wepoker如何设置透视,fishpoker透视,真是存在有挂(讲解有挂)1、完成辅助器...
据权威媒体报道!wpk透视工作... 据权威媒体报道!wpk透视工作室,智星德州插件2024最新版,一贯真的是有挂(确实有挂);1、智星德...
揭秘真相!智星德州有脚本吗,哈... 揭秘真相!智星德州有脚本吗,哈糖大菠萝有挂吗,都是真的有挂(详细教程)1、超多福利:超高返利,海量正...
据相关数据显示!佛手在线有挂吗... 据相关数据显示!佛手在线有挂吗,智星德州插件2024最新版,一贯是有挂(有挂规律)1、智星德州插件2...
盘点一款!悦扑克脚本,wepo... 盘点一款!悦扑克脚本,wepoker怎么设置盖牌,原来是有挂(确实有挂)一、游戏安装教程牌型概率发牌...
目前!wepoker高级辅助,... 目前!wepoker高级辅助,德普之星透视辅助插件,竟然确实有挂(发现有挂)在进入德普之星透视辅助插...
发现玩家!哈糖大菠萝有挂吗5个... 发现玩家!哈糖大菠萝有挂吗5个常用方法,wepoker代打辅助,果然存在有挂(讲解有挂)1、辅助软件...