angular - Angular 6:空路径绕过身份验证保护
问题描述
我正在尝试使用 Angular 路由器,但在空路径上遇到问题。这是我的路线:
const routes: Routes = [
{ path: 'feed', loadChildren: './feed/feed.module#FeedModule', canLoad: [AuthGuardService] },
{ path: 'login', component: LoginPage },
{ path: 'register', component: RegisterPage },
{ path: '', redirectTo: '/feed', pathMatch: 'full' },
{ path: '**', redirectTo: '/' }
];
我的 AuthGuardService 有一个 canLoad 方法,它总是返回 false 并重定向到 '/login' 路径:
...
@Injectable()
export class AuthGuardService implements CanLoad {
constructor(private router: Router) {
}
canLoad(route: Route): boolean {
this.router.navigate([ '/login' ]);
return false;
}
}
当我转到“localhost:4200/feed”时,我被重定向到“/login”。
但是,如果我转到 'localhost:4200/',则忽略身份验证保护并显示我的提要模块的组件。
你知道为什么吗?
谢谢 !
解决方案
我的场景中有一个工作代码。检查这个,如果它可以帮助你。
您可以使用 canActivate 代替 canLoad。
canActivate用于防止未经授权的用户
canLoad用于防止应用程序的整个模块
在下面的示例中,如果您希望使用 canLoad 代替,可以将canActivate替换为canLoad 。
import { Injectable } from '@angular/core';
import { Router, CanActivate, ActivatedRouteSnapshot, RouterStateSnapshot } from '@angular/router';
@Injectable()
export class AuthGuard implements CanActivate {
constructor(private router: Router) { }
canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot) {
if (localStorage.getItem('currentUser')) {
// logged in so return true
return true;
}
// not logged in so redirect to login page with the return url
this.router.navigate(['/login'], { queryParams: { returnUrl: state.url }});
return false;
}
}
在编写路线时,您可以定义如下。
{ path: 'newLeaveRequest', component: NewLeaveRequestComponent, canActivate: [AuthGuard]},
{ path: 'pastLeaveRequests', component: PastLeaveRequestComponent, canActivate: [AuthGuard]},
在 app.module.ts 中定义 provider 中的 AuthGuard。
推荐阅读
- android - 当设备睡眠或屏幕关闭时,Jobscheduler 仍在运行?
- c# - 将 Where() 用于 Azure 移动服务的问题
- python - PySide 打开一个新窗口,但立即关闭
- c - 从文件读取时令人困惑的分段错误
- c# - 如何将接口与通用对象一起使用?
- c# - 将 c# 应用程序与 SQL Server 镜像服务器连接
- c++ - 我编译了这个看似不正确的代码,但我不明白为什么
- android - 在 android 上使用 RecyclerView 和 Fragment 时出错
- angular - 如何在表单数组内的自动完成中添加服务中的数据?
- php - 如何验证该值是否已存在。PHP