dan*_*020 2 angular angular-router-guards
我正在使用Angular v6,如果用户没有登录,我已经实现了从仪表板到登录页面的重定向.
我对这两个选项感到困惑:
这个案例有什么更好的解决方案?
在路由模块中使用Authentication Guard这将使您可以轻松检查用户是否登录
为了更好地理解Auth Guard,以下是一些可能对您有所帮助的链接:
http://jasonwatmore.com/post/2018/05/23/angular-6-jwt-authentication-example-tutorial
如何使用angular 6 Route Auth Guards用于所有路由Root和Child Routes?
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] },
];
Run Code Online (Sandbox Code Playgroud)
这是我的授权服务:
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;
}
}
Run Code Online (Sandbox Code Playgroud)
这是您在代码中实现auth guard的方法.