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

相关内容

热门资讯

透视辅助!aapoker透视插... 透视辅助!aapoker透视插件,xpoker辅助神器(详细辅助必赢方法)1、很好的工具软件,可以解...
wepoke黑科技!wopok... wepoke黑科技!wopoker轻量版外挂(透视)真是是有挂(详细辅助曝光教程)1、超多福利:超高...
透视存在!wepoker透视底... 透视存在!wepoker透视底牌脚本,wepoker破解器(详细辅助曝光教程);wepoker透视底...
微扑克辅助机器人!wpk德州a... 1、微扑克辅助机器人!wpk德州ai机器人(透视)从前真的是有挂(详细辅助必备教程);代表性(透视辅...
透视辅助!aapoker可以开... 透视辅助!aapoker可以开挂吗,黑侠破解wepoker(详细辅助细节揭秘);1、构建自己的aap...
透视脚本!aapoker辅助工... 透视脚本!aapoker辅助工具存在吗,hh poker透视器下载(详细辅助技巧教程);1)aapo...
透视软件!wpk有没有脚本,h... 透视软件!wpk有没有脚本,hhpoker有没有辅助(详细辅助2025新版教程);1、wpk有没有脚...
透视系统!aapoker透视脚... 透视系统!aapoker透视脚本安装包,wepoker怎么提高运气(详细辅助安装教程)暗藏猫腻,小编...
透视安装!智星德州有脚本吗,哈... 透视安装!智星德州有脚本吗,哈糖大菠萝软件下载(详细辅助AI教程)1、智星德州有脚本吗ai机器人多个...
透视新版!wpk辅助器下载,a... 透视新版!wpk辅助器下载,aapoker辅助怎么用(详细辅助技巧教程)1、下载好wpk辅助器下载辅...