这是我在 app.module.ts 文件中路由的角度代码。
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;
}
}
有人能帮我吗..........