我设置了我的应用程序,其中许多组件都受到保护。但是,用户仍然可以访问主页“ /”。我想知道如果不对用户进行身份验证而不将我的所有组件的子组件都放在“ /”上的任何子组件中,是否可以将用户重定向到/ login。我将在下面提供我的修改后的版本:
Permission Denied
You don't have the proper permissions to view this page. Please contact the owner of this project to request permission.
是否可以将我的GuardService添加到我的应用程序根组件中?
答案 0 :(得分:2)
您可以在与登录相同的级别上创建无组件路由,并在该路由内移动除登录以外的所有内容。然后将守卫添加到该路由。
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以获取更多信息
答案 1 :(得分:1)
在构造函数中的应用根组件内部,您可以使用路由器从路由器捕获实例NavigationStart
。
export class AppComponent {
constructor(private router: Router) {
router.events.subscribe( (event: Event) => {
if (event instanceof NavigationStart) {
//Check either LocalStorage or cookies for value
if(!localStorage.GetItem('hasLoaded')){
this.router.navigate['./login']
}
}
});
}
}
另一个选择是路由文件中的CanDeactiveRoute
import { Injectable } from '@angular/core';
import { CanDeactivate } from '@angular/router';
import { Observable } from 'rxjs';
export interface CanComponentDeactivate {
canDeactivate: () => Observable<boolean> | Promise<boolean> | boolean;
}
@Injectable()
export class CanDeactivateGuard implements CanDeactivate<CanComponentDeactivate> {
canDeactivate(component: CanComponentDeactivate) {
return component.canDeactivate ? component.canDeactivate() : true;
}
}
将此检查与localStorage一起使用是一个好的开始,您可以使用服务器端会话和HTTP Interceptor
之类的东西。
请注意,用户可以禁用此功能,但这并不意味着隐藏或隐藏敏感数据。在使用安全传输机制的服务器上执行此操作时,已收到警告。