gpt4 book ai didi

javascript - 是否可以保护整个 Angular 应用程序?

转载 作者:行者123 更新时间:2023-11-28 17:27:49 24 4
gpt4 key购买 nike

我设置了应用程序,其中的许多组件都受到保护。然而,用户仍然能够访问主页“/”。我想知道如果用户没有经过身份验证,是否可以将用户重定向到/login,而不使我的所有组件成为我在“/”上拥有的任何组件的子组件。我将包含以下内容的修改版本:

const routes: Routes = [
{
path: "login",
component: LoginComponent
},
{
path: "test",
component: TestComponent
},
{
path: "protected",
canActivate: [AuthGuardService],
component: ProtectedComponent
},
{
path: "alsoprotected/:id",
component: AlsoProtectedComponent,
canActivate: [AuthGuardService],
children: [
{ path: "child1", component: ChildOneComponent},
{ path: "child2", component: ChildTwoComponent},
{ path: "child3", component: ChildThreeComponent },
{ path: "child4", component: ChildFourComponent },
{ path: "child5", component: ChildFiveComponent },
{ path: "child6", component: ChildSixComponent },
{ path: "child7", component: ChildSevenComponent }
]
},
{
path: "protectedsettings",
canActivate: [AuthGuardService],
component: SettingsComponent
}
];

有什么方法可以将我的 GuardService 添加到我的应用程序根组件中吗?

最佳答案

您可以在与登录相同的级别中创建无组件路由,并将除登录之外的所有内容移至该路由内。然后将守卫添加到该路线。

        const routes: Routes = [
{
path: "login",
component: LoginComponent
},
{
path: "",
canActivate: [AuthGuardService],
children: [
{
path: "test",
component: TestComponent
},
{
path: "protected",
canActivate: [AuthGuardService],
component: ProtectedComponent
},
{
path: "alsoprotected/:id",
component: AlsoProtectedComponent,
canActivate: [AuthGuardService],
children: [
{path: "child1", component: ChildOneComponent},
{path: "child2", component: ChildTwoComponent},
{path: "child3", component: ChildThreeComponent},
{path: "child4", component: ChildFourComponent},
{path: "child5", component: ChildFiveComponent},
{path: "child6", component: ChildSixComponent},
{path: "child7", component: ChildSevenComponent}
]
},
{
path: "protectedsettings",
canActivate: [AuthGuardService],
component: SettingsComponent
}
]
}
];

检查这个link了解更多信息

关于javascript - 是否可以保护整个 Angular 应用程序?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51178052/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com