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

相关内容

热门资讯

透视教程书!破解辅助插件wep... 透视教程书!破解辅助插件wepoker(透视)都是有辅助平台(哔哩哔哩)运破解辅助插件wepoker...
透视资料!WePoKer辅助器... 透视资料!WePoKer辅助器(透视)其实有辅助神器(哔哩哔哩)1、全新机制【WePoKer辅助器a...
透视妙招!aapoker辅助软... 透视妙招!aapoker辅助软件合法吗(透视)都是真的是有辅助辅助器(哔哩哔哩)1、aapoker辅...
透视要领!wepoker挂(透... 透视要领!wepoker挂(透视)都是是有辅助下载(哔哩哔哩)1、进入游戏-大厅左侧-新手福利-激活...
透视经验!wepoker透视是... 透视经验!wepoker透视是真的吗(透视)果然真的有辅助神器(哔哩哔哩)wepoker透视是真的吗...
透视秘籍!wepoker透视脚... 透视秘籍!wepoker透视脚本免费app(透视)一直存在有辅助工具(哔哩哔哩)1、超多福利:超高返...
透视模块!德州之星扫描器(透视... 透视模块!德州之星扫描器(透视)都是有辅助辅助器(哔哩哔哩)运德州之星扫描器辅助工具,进入游戏界面。...
透视步骤!wepoker怎么获... 透视步骤!wepoker怎么获得好牌(透视)都是存在有辅助软件(哔哩哔哩)1、金币登录送、破产送、升...
透视法门!福建大菠萝万能辅助器... 透视法门!福建大菠萝万能辅助器(透视)都是是真的辅助软件(哔哩哔哩)1、透视法门!福建大菠萝万能辅助...
透视要领!pokeplus脚本... 透视要领!pokeplus脚本(透视)本来有辅助安装(哔哩哔哩)1、pokeplus脚本透视辅助软件...