Angular 如果用户已登录,则角度重定向到仪表板
我使用的是Angular v6,如果用户未登录,我将实现从仪表板到登录页面的重定向。Angular 如果用户已登录,则角度重定向到仪表板,angular,angular-router-guards,Angular,Angular Router Guards,我使用的是Angular v6,如果用户未登录,我将实现从仪表板到登录页面的重定向。 我对这两种选择感到困惑: 添加登录保护文件以检查登录状态并重定向到仪表板 检测路由更改事件,检查此处的登录状态并重定向 对于这种情况,什么是更好的解决方案?使用guard是一个不错的选择 请检查链接 在路由模块中使用身份验证保护,这将使您更容易检查用户是否登录 为了更好地了解Auth Guard,这里有一些链接可以帮助您: 这是我在项目中使用的代码 在应用程序模块文件中,我使用的auth guard
我对这两种选择感到困惑:
对于这种情况,什么是更好的解决方案?使用guard是一个不错的选择 请检查链接
在路由模块中使用身份验证保护,这将使您更容易检查用户是否登录 为了更好地了解Auth Guard,这里有一些链接可以帮助您: 这是我在项目中使用的代码 在应用程序模块文件中,我使用的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;
}
}
这就是如何在代码中实现auth-guard的方法。Yahh您在几分钟内提供了一些示例,这是正确的!谢谢你的回答,我已经在回家的路上安装了auth guard。但如果您已登录,请返回登录页面。我如何重定向回主页?this.router.url=='/login'在auth guard中为此设置else if条件。检查您是否已登录并再次访问登录页面。或者你可以使用位置服务来获取url。非常感谢,我使用登录模块的ngOnInit来检查它。是的,我知道,但我在手机上回答了这个问题。并且找不到附加链接的任何选项。。。