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辅助软件视频(透视)竟然真的有辅助插件(有挂方针)-哔哩哔哩wepoke...
无独有偶!wepoker私人局... 无独有偶!wepoker私人局辅助挂(透视)总是是有辅助工具(发现有挂)-哔哩哔哩1.wepoker...
透视好友房!pokernow辅... 透视好友房!pokernow辅助工具(透视)原来真的是有辅助app(有挂技术)-哔哩哔哩1、poke...
据通报!wepoker数据分析... 据通报!wepoker数据分析(透视)确实有辅助插件(有挂技术)-哔哩哔哩1、起透看视 wepoke...
今天上午!wepoker免费辅... 今天上午!wepoker免费辅助器(透视)一直真的有辅助下载(有挂规律)-哔哩哔哩1、下载好wepo...
透视ai代打!wepoker游... 透视ai代打!wepoker游戏下载(透视)一直是真的辅助安装(有挂秘诀)-哔哩哔哩透视ai代打!w...
今天下午!wepoker有没有... 今天下午!wepoker有没有机器人(透视)本来是真的辅助平台(有挂分析)-哔哩哔哩1、wepoke...
有了最新消息!aapoker公... 有了最新消息!aapoker公共底牌(透视)一直存在有辅助插件(有挂方针)-哔哩哔哩1、进入游戏-大...
透视实锤!德州局透视脚本免费版... 透视实锤!德州局透视脚本免费版下载手机版(透视)竟然真的有辅助插件(有挂方法)-哔哩哔哩一、德州局透...
透视私人局!uupoker透视... 透视私人局!uupoker透视(透视)一直真的有辅助工具(真是有挂)-哔哩哔哩1、首先打开uupok...