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

相关内容

热门资讯

有挂透视!pokemomo辅助... 有挂透视!pokemomo辅助工具,德州真人透视脚本(透视)果然真的有辅助方法(哔哩哔哩)1、很好的...
专业透视!pokerworld... 专业透视!pokerworld软件,epoker免费透视脚本(透视)都是一直总是有辅助方法(哔哩哔哩...
总结透视!sohoopoker... 总结透视!sohoopoker辅助,pokemmo辅助官网(透视)切实一直都是有辅助app(哔哩哔哩...
了解透视!拱趴大菠萝作必弊方法... 了解透视!拱趴大菠萝作必弊方法,聚星ai辅助工具下载(透视)好像是真的有辅助神器(哔哩哔哩)1、每一...
开挂透视!来玩app破解版,扑... 开挂透视!来玩app破解版,扑克之星辅助(透视)都是真的是有辅助技巧(哔哩哔哩)1、完成扑克之星辅助...
普及透视!pokermaste... 普及透视!pokermaster破解版,拱趴大菠萝万能挂(透视)其实一直都是有辅助工具(哔哩哔哩)1...
解谜透视!德州局脚本,智星德州... 解谜透视!德州局脚本,智星德州插件最新版本更新内容详解(透视)果然真的是有辅助插件(哔哩哔哩)1、智...
辅助透视!约局吧能不能开挂,w... 辅助透视!约局吧能不能开挂,werplan透视挂(透视)确实一直总是有辅助工具(哔哩哔哩);一、约局...
了解透视!云扑克有透视吗,红龙... 了解透视!云扑克有透视吗,红龙poker辅助器免费观看(透视)本来真的有辅助脚本(哔哩哔哩)1、不需...
揭露透视!pokemmo修改器... 揭露透视!pokemmo修改器手机版,pokerworld软件(透视)一贯有辅助神器(哔哩哔哩)1、...