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

相关内容

热门资讯

攻略讲解!We poker辅助... 攻略讲解!We poker辅助器下载(辅助挂)切实是真的有挂(了解有挂)1、We poker辅助器下...
一分钟了解!德普之星透视(辅助... 一分钟了解!德普之星透视(辅助挂)其实有挂(有挂细节)一分钟了解!德普之星透视(辅助挂)其实有挂(有...
详细说明!wepoker有用吗... 详细说明!wepoker有用吗(辅助挂)本来真的有挂(有挂分享);1、用户打开应用后不用登录就可以直...
热点推荐!wepoker辅助分... 热点推荐!wepoker辅助分析器(辅助挂)确实真的是有挂(有挂神器)1、在wepoker辅助分析器...
推荐一款!hhpoker透视工... 推荐一款!hhpoker透视工具(辅助挂)一直有挂(有挂教学);1、不需要AI权限,帮助你快速的进行...
一分钟了解!wepoker私人... 一分钟了解!wepoker私人局透视插件(辅助挂)一贯存在有挂(揭秘有挂)1、完成wepoker私人...
实测必看!hhpoker辅助软... 实测必看!hhpoker辅助软件(辅助挂)一直有挂(有挂解密)1、上手简单,内置详细流程视频教学,新...
必知教程!pokemmo修改器... 必知教程!pokemmo修改器手机版(辅助挂)果然有挂(有挂详情)1、任何pokemmo修改器手机版...
推荐一款!微扑克微乐辅助(辅助... 推荐一款!微扑克微乐辅助(辅助挂)竟然有挂(有挂教程)1、下载好微扑克微乐辅助脚本下载之后点击打开,...
一分钟秒懂!wepoker透视... 一分钟秒懂!wepoker透视脚本免费下载(辅助挂)一贯存在有挂(果真有挂)1、wepoker透视脚...