【发布时间】:2019-03-20 22:26:42
【问题描述】:
在模板组件AppComponent中,变量this.loggedInService.isLoggedIn根据值在logIn()和logout()方法之间切换,在应用组件AppComponent中订阅服务@中的这些方法987654326@ 并根据方法,将变量的值更改为 true 或 false。
同样在Guard的方法checkLogin (url: string)中,我根据变量this.loggedInService.isLoggedIn的值返回true或false
一切正常,但是当我重置页面时,我需要保留输入或输出按钮的值。我尝试在服务中的login() 和logout() 方法中执行此操作,但重新加载页面后,更改仍未保存。帮助解决此问题,以便在页面重新启动后保留更改。
AppComponent 的模板:
<li class="nav-item">
<a class="btn btn-outline-success"
[class.btn-outline-success]="!this.loggedInService.isLoggedIn"
[class.btn-outline-danger]="this.loggedInService.isLoggedIn"
(click)="this.loggedInService.isLoggedIn ? logout() : logIn()">
{{this.loggedInService.isLoggedIn ? 'Exit' : 'Enter'}}
</a>
</li>
AppComponent代码:
export class AppComponent implements OnInit {
constructor(private loggedInService: LoggedinService,
private router: Router) {
}
ngOnInit() {}
logIn(): void {
this.loggedInService.login();
if (this.loggedInService.isLoggedIn) {
let redirect = this.loggedInService.redirectUrl ? this.loggedInService.redirectUrl :
'/gallery';
this.router.navigate([redirect]);
}
}
logout(): void {
this.loggedInService.logout();
this.router.navigate(['/']);
}
}
登录服务:
export class LoggedinService implements OnInit {
isLoggedIn: boolean = false;
redirectUrl: string;
constructor() {
}
ngOnInit() {
this.CheckAuthentication();
}
enter code here
CheckAuthentication(): boolean {
if (localStorage.getItem('login') === 'true') {
return this.isLoggedIn = true;
} else if (localStorage.getItem('login') === 'false') {
return this.isLoggedIn = false;
}
}
login() {
localStorage.setItem('login', 'true')
}
logout() {
localStorage.removeItem('login');
localStorage.setItem('login', 'false')
}
AuthGuard:
export class AuthGuard implements CanActivate {
constructor(private loggedInService: LoggedinService) {
}
canActivate(next: ActivatedRouteSnapshot,
state: RouterStateSnapshot): boolean{
let url: string = state.url;
return this.checkLogin(url);
}
checkLogin(url: string): boolean {
if (this.loggedInService.isLoggedIn) {
return true;
} else {
this.loggedInService.redirectUrl = url;
return false;
}
}
}
【问题讨论】:
-
localStorage.removeItem('login');为什么下一行的localStorage.getItem('login')会返回null以外的任何内容?它看起来像一个多线程守卫,但我认为它不能在多线程环境中工作。
标签: javascript angular typescript local-storage storage