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怎么拿到好牌,wejoker黑侠辅助器,一贯一直都是有辅助脚本(哔哩哔哩)1...
关于透视!we-poker辅助... 关于透视!we-poker辅助软件教程,wepoker轻量版透视方法,一直是真的有辅助技巧(哔哩哔哩...
揭露透视!hhpoker德州透... 揭露透视!hhpoker德州透视,hhpoker怎么防作比弊,竟然是真的有辅助插件(哔哩哔哩)1、完...
科普透视!aapoker透视怎... 科普透视!aapoker透视怎么用,aapoker怎么拿好牌,一直有辅助教程(哔哩哔哩)1、玩家可以...
普及透视!wepoker辅助软... 普及透视!wepoker辅助软件视频,wepoker养号规律,其实一直都是有辅助方法(哔哩哔哩);在...
了解透视!wpk显示有作比弊,... 了解透视!wpk显示有作比弊,wpk透视工作室,其实有辅助软件(哔哩哔哩)1、首先打开辅助器下载最新...
揭幕透视!hhpoker透视脚... 揭幕透视!hhpoker透视脚本,hhpoker外g挂靠谱吗,一直真的是有辅助工具(哔哩哔哩)一、可...
开挂透视!wepoker买钻石... 开挂透视!wepoker买钻石有用吗,wepoker科技辅助器,总是存在有辅助app(哔哩哔哩)1、...
解迷透视!hhpoker有后台... 解迷透视!hhpoker有后台操作吗,hhpoker辅助软件是真的么,一直存在有辅助技巧(哔哩哔哩)...
有挂透视!wepoker辅助器... 有挂透视!wepoker辅助器激活码,wepoker辅助透视软件,好像一直都是有辅助神器(哔哩哔哩)...