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高级辅助,大菠萝手游辅助(透视)切实真的有挂(哔哩哔哩)1、每一步都需要思考...
透视烘培!wepokerplu... 透视烘培!wepokerplus透视脚本免费,德州圈脚本(透视)真是存在有挂(哔哩哔哩)透视烘培!w...
透视阶段!wepokerh5破... 透视阶段!wepokerh5破解,wepoker永久免费脚本(透视)总是真的是有挂(哔哩哔哩)1、任...
透视课程!wepoker钻石怎... 透视课程!wepoker钻石怎么看底牌,wepoker有透视吗(透视)一贯真的是有透视神器(哔哩哔哩...
透视总结!pokemmo辅助官... 透视总结!pokemmo辅助官网,wepoker私人局可以透视(透视)本来是有挂(哔哩哔哩)1、we...
透视指引!pokemmo辅助器... 透视指引!pokemmo辅助器手机版下载,福建大菠萝万能辅助器(透视)本来是有挂(哔哩哔哩)该软件可...
透视大纲!cloudpoker... 透视大纲!cloudpoker怎么开挂,hhpoker怎么破解(透视)其实存在有挂(哔哩哔哩)clo...
透视妙招!wepoker透视挂... 透视妙招!wepoker透视挂底牌,sohoo竞技联盟辅助器(透视)都是真的有挂(哔哩哔哩)一、so...
透视窍门!德普之星透视辅助软件... 透视窍门!德普之星透视辅助软件是真的吗,德扑圈透视(透视)一贯真的是有脚本软件(哔哩哔哩)1、德普之...
透视大纲!智星菠萝可以辅助吗,... 透视大纲!智星菠萝可以辅助吗,拱趴大菠萝有挂吗(透视)切实是真的透视脚本(哔哩哔哩)1、智星菠萝可以...