使用angular 2个守卫。如何在刷新页面时保持用户登录状态?
Using angular 2 guard. How to Keep user logged in when refreshing the page?
这是我在 app.module.ts 文件中的 angular 路由代码。
const appRoutes: Routes = [
{path: '', component: LoginformComponent},
{path: 'dashboard', component: DashboardComponent, canActivate: [AuthenticationGuard]},
{path: 'user', children: [
{path: '', component: UserComponent},
{path: ':id', component: UserdetailComponent}
], canActivate: [AuthenticationGuard]
},
{path: '**', component: NotfoundComponent}
];
下面的代码代表守卫文件。
export class AuthenticationGuard implements CanActivate {
constructor(private user: UserService, private router: Router) {}
canActivate(next: ActivatedRouteSnapshot, state: RouterStateSnapshot): boolean {
if (! this.user.getUserLoggedIn()) {
this.router.navigate(['/']);
}
return this.user.getUserLoggedIn();
}
}
当我以用户身份登录时,Guard 工作正常。但如果刷新它,它会注销我。我想要一种即使在刷新页面后也能让我保持登录状态的方法?
这是用户service.ts文件,
@Injectable()
export class UserService {
private isUserLoggedIn: boolean;
private username: string;
constructor() {
this.isUserLoggedIn = false;
}
setUserLoggedIn(username) {
this.isUserLoggedIn = true;
this.username = username;
}
getUserLoggedIn() {
return this.isUserLoggedIn;
}
getUserName() {
return this.username;
}
}
谁能帮帮我..........
当您刷新页面时,整个应用程序将再次加载,即组件再次经历其生命周期。根据应用程序的体系结构,您需要保存身份验证信息,以便在页面刷新之间保持不变。
工作时最常使用 JWT Angular,但并非总是如此。如果您使用的是 JWT,则应将 JWT 令牌保存在 cookie 中,并在应用重新加载时检查它是否存在。如果它退出,从 cookie 中读取它并正常继续,否则要求用户重新登录。
这是我在 app.module.ts 文件中的 angular 路由代码。
const appRoutes: Routes = [
{path: '', component: LoginformComponent},
{path: 'dashboard', component: DashboardComponent, canActivate: [AuthenticationGuard]},
{path: 'user', children: [
{path: '', component: UserComponent},
{path: ':id', component: UserdetailComponent}
], canActivate: [AuthenticationGuard]
},
{path: '**', component: NotfoundComponent}
];
下面的代码代表守卫文件。
export class AuthenticationGuard implements CanActivate {
constructor(private user: UserService, private router: Router) {}
canActivate(next: ActivatedRouteSnapshot, state: RouterStateSnapshot): boolean {
if (! this.user.getUserLoggedIn()) {
this.router.navigate(['/']);
}
return this.user.getUserLoggedIn();
}
}
当我以用户身份登录时,Guard 工作正常。但如果刷新它,它会注销我。我想要一种即使在刷新页面后也能让我保持登录状态的方法?
这是用户service.ts文件,
@Injectable()
export class UserService {
private isUserLoggedIn: boolean;
private username: string;
constructor() {
this.isUserLoggedIn = false;
}
setUserLoggedIn(username) {
this.isUserLoggedIn = true;
this.username = username;
}
getUserLoggedIn() {
return this.isUserLoggedIn;
}
getUserName() {
return this.username;
}
}
谁能帮帮我..........
当您刷新页面时,整个应用程序将再次加载,即组件再次经历其生命周期。根据应用程序的体系结构,您需要保存身份验证信息,以便在页面刷新之间保持不变。
工作时最常使用 JWT Angular,但并非总是如此。如果您使用的是 JWT,则应将 JWT 令牌保存在 cookie 中,并在应用重新加载时检查它是否存在。如果它退出,从 cookie 中读取它并正常继续,否则要求用户重新登录。