Angular7 路由重定向用户
Angular7 route redirect user
如果用户登录,它会自动重定向到 route: ''
并且我将令牌存储在 localStorage 中。
但是,如果登录用户手动输入 url route: /login
,他应该在 route: ''
中被路由,这就是我想要实现的。
我所做的是在我的 OnInit()
中添加一个验证到我的 LoginComponent
中并且它正在工作。但是我怎样才能在我的 AuthGuard 中实现这个呢?如果 route: /login
我正在考虑获取请求的路线,如果已经登录则导航到 route: ''
。
路线:
{ path: '', component: PostListComponent },
{ path: 'create', component: PostCreateComponent, canActivate: [AuthGuard] },
{ path: 'edit/:postId', component: PostCreateComponent, canActivate: [AuthGuard] },
{ path: 'login', component: LoginComponent }
AuthGuard:
const currentRoute = route.url[0].path;
const isAuth = this.authService.getIsAuth();
if (!isAuth) {
this.router.navigate(['/login']);
}
if (currentRoute === '/login') {
this.router.navigate(['/']);
}
console.log(currentRoute);
return isAuth;
登录组件:
ngOnInit() {
const isAuth = this.authService.getIsAuth();
if (isAuth) {
this.router.navigate(['/']);
}
}
更新:我更新了我的 AuthGuard 以检查当前路由,但如果在地址栏中手动输入路由,它不会获取路由。
在进一步审查我的代码和浏览 Whosebug 之后,我提出了一个解决方案,但我不确定可能的安全性。如果您有更好的方法,请分享。
路线:
{ path: 'login', component: LoginComponent, canActivate: [AuthGuard] }
AuthGuard:
const currentRoute = route.url[0].path;
let isAuth = this.authService.getIsAuth();
if (isAuth) {
if (currentRoute === 'login') {
this.router.navigate(['/']);
}
} else {
if (currentRoute === 'login') {
isAuth = true;
} else {
this.router.navigate(['/login']);
}
}
return isAuth;
isAuth
returns 布尔值是否经过身份验证,在 AuthGuard 中,我使用了 let
并将值更改为 true
.
如果用户登录,它会自动重定向到 route: ''
并且我将令牌存储在 localStorage 中。
但是,如果登录用户手动输入 url route: /login
,他应该在 route: ''
中被路由,这就是我想要实现的。
我所做的是在我的 OnInit()
中添加一个验证到我的 LoginComponent
中并且它正在工作。但是我怎样才能在我的 AuthGuard 中实现这个呢?如果 route: /login
我正在考虑获取请求的路线,如果已经登录则导航到 route: ''
。
路线:
{ path: '', component: PostListComponent },
{ path: 'create', component: PostCreateComponent, canActivate: [AuthGuard] },
{ path: 'edit/:postId', component: PostCreateComponent, canActivate: [AuthGuard] },
{ path: 'login', component: LoginComponent }
AuthGuard:
const currentRoute = route.url[0].path;
const isAuth = this.authService.getIsAuth();
if (!isAuth) {
this.router.navigate(['/login']);
}
if (currentRoute === '/login') {
this.router.navigate(['/']);
}
console.log(currentRoute);
return isAuth;
登录组件:
ngOnInit() {
const isAuth = this.authService.getIsAuth();
if (isAuth) {
this.router.navigate(['/']);
}
}
更新:我更新了我的 AuthGuard 以检查当前路由,但如果在地址栏中手动输入路由,它不会获取路由。
在进一步审查我的代码和浏览 Whosebug 之后,我提出了一个解决方案,但我不确定可能的安全性。如果您有更好的方法,请分享。
路线:
{ path: 'login', component: LoginComponent, canActivate: [AuthGuard] }
AuthGuard:
const currentRoute = route.url[0].path;
let isAuth = this.authService.getIsAuth();
if (isAuth) {
if (currentRoute === 'login') {
this.router.navigate(['/']);
}
} else {
if (currentRoute === 'login') {
isAuth = true;
} else {
this.router.navigate(['/login']);
}
}
return isAuth;
isAuth
returns 布尔值是否经过身份验证,在 AuthGuard 中,我使用了 let
并将值更改为 true
.