[英]Angular redirect to dashboard if user is logged in
I am using Angular v6, I have implement redirect from dashboard to login page if user is not logged in. 我正在使用Angular v6,如果用户没有登录,我已经实现了从仪表板到登录页面的重定向。
I'm confused between the two options: 我在两个选项之间感到困惑:
What is the better solution for this case ? 这个案例有什么更好的解决方案?
Use Authentication Guard in your routing module It will make things easy for you to check whether a user is login or not 在路由模块中使用Authentication Guard这将使您可以轻松检查用户是否登录
For a better understanding of Auth Guard here are some links that might help you : 为了更好地理解Auth Guard,以下是一些可能对您有所帮助的链接:
http://jasonwatmore.com/post/2018/05/23/angular-6-jwt-authentication-example-tutorial http://jasonwatmore.com/post/2018/05/23/angular-6-jwt-authentication-example-tutorial
How to use angular 6 Route Auth Guards for all routes Root and Child Routes? 如何使用angular 6 Route Auth Guards用于所有路由Root和Child Routes?
https://medium.com/@ryanchenkie_40935/angular-authentication-using-route-guards-bf7a4ca13ae3 https://medium.com/@ryanchenkie_40935/angular-authentication-using-route-guards-bf7a4ca13ae3
https://scotch.io/courses/routing-angular-2-applications/canactivate-and-canactivatechild https://scotch.io/courses/routing-angular-2-applications/canactivate-and-canactivatechild
Here is my code that I used in my project! 这是我在项目中使用的代码!
In-app module file I used auth guard like this : 应用内模块文件我使用了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] },
];
And here is my auth guard service : 这是我的授权服务:
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;
}
}
This is how you can implement auth guard in your code. 这是您在代码中实现auth guard的方法。
Using guard is good option. 使用后卫是不错的选择。
Please check link 请检查链接
http://jasonwatmore.com/post/2018/05/16/angular-6-user-registration-and-login-example-tutorial http://jasonwatmore.com/post/2018/05/16/angular-6-user-registration-and-login-example-tutorial
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.