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

相关内容

热门资讯

aapoker辅助工具存在!云... 1、aapoker辅助工具存在!云扑克软件,wepoke有挂吗网上,爆料教程(真是存在有挂)2、进入...
黑科技中牌率!(德州之星)外挂... 黑科技中牌率!(德州之星)外挂辅助软件,(德州ai)总是是真的有挂,高科技教程(有挂辅助);1.德州...
wepok软件透明挂!德扑之星... wepok软件透明挂!德扑之星隐藏功能,德州辅助软件开发定制,线上教程(素来真的有挂)准备好在德州辅...
黑科技挂!(wepoker)软... 黑科技挂!(wepoker)软件透明挂,(wepoKE)一直真的是有挂,透明挂教程(有挂攻略)这是由...
wepoke透明黑科技!云扑克... wepoke透明黑科技!云扑克是否有外挂,wepower辅助软件,新2025版(总是是有挂);原来确...
黑科技ai!(wPk)透视辅助... 黑科技ai!(wPk)透视辅助脚本,(wpK)一直是真的有挂,可靠教程(有挂技巧);实战中需综合运用...
we辅助poker德之星!红龙... we辅助poker德之星!红龙扑克有挂么,wepooke app系统规律,新2025版(最初有挂),...
黑科技模拟器!(微扑克)透视辅... 黑科技模拟器!(微扑克)透视辅助软件,(微扑克wpk)从来有挂,微扑克教程(有挂教程);1分钟了解详...
aapoker有外挂!微扑克辅... aapoker有外挂!微扑克辅助器是真的么,德扑ai自定义设置数据,爆料教程(其实有挂)是一款可以让...
黑科技ai代打!(aapokE... 黑科技ai代打!(aapokER)透明挂辅助安装,(AAPOKeR)本来真的是有挂,AI教程(有挂技...