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

相关内容

热门资讯

透视揭幕"wepok... 透视揭幕"wepokerplus辅助"本来有辅助神器(哔哩哔哩)wepokerplus辅助破解侠是真...
透视详细"wepok... 透视详细"wepoker透视有用吗"其实是有辅助攻略(哔哩哔哩)1、打开软件启动之后找到中间准星的标...
透视揭露"pokem... 透视揭露"pokemmo脚本辅助器"好像存在有辅助攻略(哔哩哔哩)1、pokemmo脚本辅助器公共底...
透视解迷"哈糖大菠萝... 透视解迷"哈糖大菠萝万能挂"总是是有辅助技巧(哔哩哔哩)该软件可以轻松地帮助玩家将哈糖大菠萝万能挂外...
透视分享"wepok... 透视分享"wepoker能不能透视"原来有辅助器(哔哩哔哩)1、完成wepoker能不能透视有辅助插...
透视解迷"pokem... 透视解迷"pokemmo手机辅助软件"好像有辅助神器(哔哩哔哩)1)pokemmo手机辅助软件辅助插...
透视揭幕"we-po... 透视揭幕"we-poker软件"切实有辅助挂(哔哩哔哩)1、点击下载安装,we-poker软件脚本分...
透视专业"wepok... 透视专业"wepoker有辅助吗"好像真的是有辅助教程(哔哩哔哩)1、点击下载安装,wepoker有...
透视详情"wepok... 透视详情"wepoker可以开透视吗"其实是真的辅助脚本(哔哩哔哩)1、操作简单,无需wepoker...
透视分享"wepok... 透视分享"wepoker是不是有人用挂"总是存在有辅助软件(哔哩哔哩)1、点击下载安装,wepoke...