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

相关内容

热门资讯

三分钟技法!wepoker透视... 三分钟技法!wepoker透视脚本安卓(透视)确实是真的有辅助辅助(哔哩哔哩)进入游戏-大厅左侧-新...
十分钟策略!wepoker有没... 十分钟策略!wepoker有没有插件(透视)原来存在有辅助插件(哔哩哔哩)1、实时wepoker有没...
第3分钟诀窍!德州来玩辅助器(... 第3分钟诀窍!德州来玩辅助器(透视)一贯真的有辅助插件(哔哩哔哩)1、德州来玩辅助器脚本辅助下载、德...
6分钟模板!wejoker开挂... 6分钟模板!wejoker开挂(透视)果然有辅助辅助(哔哩哔哩)一、wejoker开挂游戏安装教程牌...
八分钟经验!wepoker透视... 八分钟经验!wepoker透视脚本安卓(透视)一直真的是有辅助下载(哔哩哔哩)进入游戏-大厅左侧-新...
第1分钟窍要!hhpoker透... 第1分钟窍要!hhpoker透视脚本下载(透视)一直真的是有辅助下载(哔哩哔哩)1、第1分钟窍要!h...
第九分钟手段!wpk辅助(透视... 第九分钟手段!wpk辅助(透视)都是真的是有辅助安装(哔哩哔哩)1、第九分钟手段!wpk辅助(透视)...
第五分钟阶段!hh poker... 第五分钟阶段!hh poker透视器下载(透视)总是是真的有辅助教程(哔哩哔哩)亲,关键说明,hh ...
第五分钟指南!wepoker游... 第五分钟指南!wepoker游戏的安装教程(透视)其实真的有辅助脚本(哔哩哔哩)1、玩家可以在wep...
六分钟讲义!wpk辅助是什么(... 六分钟讲义!wpk辅助是什么(透视)竟然有辅助安装(哔哩哔哩)亲,关键说明,wpk辅助是什么透视脚本...