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

相关内容

热门资讯

近日!pokemmo辅助器手机... 近日!pokemmo辅助器手机版下载(透视)其实是有挂的(的确有挂开挂辅助软件)-哔哩哔哩1、pok...
围绕透视问题!wepoker私... 围绕透视问题!wepoker私局代打,hhpoker真的假的,方式教程(存在有挂)-哔哩哔哩1、围绕...
这一问题亟待解决!wpk控制牌... 这一问题亟待解决!wpk控制牌是真的吗(透视)果然是有挂的(有挂讲解开挂辅助下载)-哔哩哔哩1、wp...
日前!wepoker可以透视码... 日前!wepoker可以透视码,佛手在线大菠萝技巧,方式教程(有挂助手)-哔哩哔哩1、完成佛手在线大...
现就发布提示!wejoker免... 现就发布提示!wejoker免费脚本(透视)一直确实有挂(有挂透明挂开挂辅助下载)-哔哩哔哩一、we...
现场直击!wepoker私人局... 现场直击!wepoker私人局透视插件,xpoker透视辅助,技法教程(有挂教程)-哔哩哔哩1、在w...
于此同时!hhpoker辅助码... 于此同时!hhpoker辅助码怎么用(透视)果然真的有挂(有挂方略开挂辅助平台)-哔哩哔哩1、在hh...
备受关注的!wepoker买钻... 备受关注的!wepoker买钻石有用吗,wepoker一直输的号能继续打吗,要领教程(有挂秘诀)-哔...
据文件显示!哈糖大菠萝助手(透... 据文件显示!哈糖大菠萝助手(透视)果然是有挂的(有挂助手开挂辅助神器)-哔哩哔哩;1、哈糖大菠萝助手...
现就发布提示!aapoker俱... 现就发布提示!aapoker俱乐部靠谱吗,wepoker模拟器哪个,模块教程(有挂攻略)-哔哩哔哩1...