我正在使用 Angular v6,如果用户未登录,我已经实现了从仪表板到登录页面的重定向。
我对这两个选项感到困惑:
- 添加登录保护文件以检查登录状态并重定向到仪表板
- 检测路由更改事件,在此处检查登录状态并重定向
这种情况下更好的解决方案是什么?
我正在使用 Angular v6,如果用户未登录,我已经实现了从仪表板到登录页面的重定向。
我对这两个选项感到困惑:
这种情况下更好的解决方案是什么?
在您的路由模块中使用 Authentication Guard 它可以让您轻松检查用户是否登录
为了更好地理解 Auth Guard,这里有一些可能对您有所帮助的链接:
http://jasonwatmore.com/post/2018/05/23/angular-6-jwt-authentication-example-tutorial
如何为所有路由根路由和子路由使用 angular 6 Route Auth Guards?
https://medium.com/@ryanchenkie_40935/angular-authentication-using-route-guards-bf7a4ca13ae3
https://scotch.io/courses/routing-angular-2-applications/canactivate-and-canactivatechild
这是我在项目中使用的代码!
我使用的应用内模块文件是这样的 auth guard:
const ROUTES = [
{ path: '', redirectTo: 'home', pathMatch: 'full' },
{ path: 'login', component: LoginComponent },
{ path: 'register', component: RegisterComponent },
{ path: 'home', component: HomeComponent },
{ path: 'books', component: BookComponent,canActivate:[AuthGuardService] },
{ path: 'book-details/:id', component: BookDetailComponent,canActivate:[AuthGuardService] },
{ path: 'book-create', component: BookCreateComponent,canActivate:[AuthGuardService] },
];
这是我的身份验证服务:
import { Injectable } from '@angular/core';
import { Router, CanActivate } from '@angular/router';
@Injectable()
export class AuthGuardService implements CanActivate {
constructor( public router: Router) { }
canActivate(): boolean {
if (sessionStorage.getItem('id') == null) {
this.router.navigate(['home']);
return false;
}
return true;
}
}
这就是您可以在代码中实现身份验证保护的方式。
使用警卫是不错的选择。
请检查链接
http://jasonwatmore.com/post/2018/05/16/angular-6-user-registration-and-login-example-tutorial