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

相关内容

热门资讯

玩家必知教程!wejoker辅... 玩家必知教程!wejoker辅助软件视频,aapoker能控制牌吗,详细教程!(果然是有挂的)-哔哩...
热门推荐!werplan怎么透... 【福星临门,好运相随】;热门推荐!werplan怎么透视,德州之星扫描器,2026新版技巧(一直真的...
一分钟揭秘!wepokerpl... 一分钟揭秘!wepokerplus辅助,hh poker辅助器先试用,揭秘攻略(一贯是有挂的)-哔哩...
终于清楚!newpoker怎么... 终于清楚!newpoker怎么安装脚本,we-poker软件,力荐教程(一直是有挂的)-哔哩哔哩;1...
揭秘关于!wepoker钻石怎... 揭秘关于!wepoker钻石怎么看底牌,德普之星的辅助工具介绍,必胜教程(一直确实有挂)-哔哩哔哩;...
一分钟揭秘!uupoker有透... 一分钟揭秘!uupoker有透视吗,hhpoker有没有辅助,新2026版(一贯真的有挂)-哔哩哔哩...
科技通报!hhpoker为什么... 科技通报!hhpoker为什么一直输,wepoker透视脚本苹果版,存在挂教程(原来有挂)-哔哩哔哩...
透视辅助!wepokerplu... 透视辅助!wepokerplus透视脚本免费,wepoker辅助插件功能,必备教程(一贯有挂)-哔哩...
透视辅助!wejoker内置辅... 透视辅助!wejoker内置辅助,hhpoker有辅助的吗,wpk教程(其实真的有挂)-哔哩哔哩,h...
一分钟了解!wepoker透视... 一分钟了解!wepoker透视脚本下载,wepoker怎么看牌型,黑科技教程(其实真的是有挂)-哔哩...