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

相关内容

热门资讯

此事备受玩家关注!pokemm... 此事备受玩家关注!pokemmo手机版透视脚本(透视)新九哥破解版(确实是有辅助平台)-哔哩哔哩该软...
为了进一步!哈糖大菠萝软件下载... 为了进一步!哈糖大菠萝软件下载(透视)九游辅助真的假的(切实存在有辅助插件)-哔哩哔哩九游辅助真的假...
今天上午!aapoker怎么拿... 今天上午!aapoker怎么拿好牌(透视)决战卡五星辅助软件哪个好用(一贯存在有辅助辅助器)-哔哩哔...
最终!we-poker正规吗(... 最终!we-poker正规吗(透视)蜀山四川智能辅助软件(竟然是真的辅助安装)-哔哩哔哩1、下载好蜀...
透视脚本!steampoker... 透视脚本!steampokermaster辅助(透视)心悦海南辅助(一贯真的有辅助软件)-哔哩哔哩1...
透视透视!cloudpoker... 透视透视!cloudpoker作必弊(透视)手游蛮王辅助(原来存在有辅助app)-哔哩哔哩手游蛮王辅...
透视辅助!购买的wpk辅助在哪... 透视辅助!购买的wpk辅助在哪里下载(透视)上游辅助器(原来真的有辅助工具)-哔哩哔哩1、任何上游辅...
透视好牌!哈糖大菠萝可以开挂吗... 透视好牌!哈糖大菠萝可以开挂吗(透视)天天互娱网络科技(一贯是有辅助安装)-哔哩哔哩;1、首先打开哈...
透视计算!wepoker辅助器... 透视计算!wepoker辅助器如何使用(透视)新畅游互娱辅助(原来存在有辅助平台)-哔哩哔哩1、每一...
据文件显示!德扑圈透视(透视)... 据文件显示!德扑圈透视(透视)吉祥填大坑攻略(一直是有辅助工具)-哔哩哔哩1、用户打开应用后不用登录...