刷新页面时如何维护变量的值

How to maintain the values of a variable when refreshing the page

我有一个 canActivate 方法。当我在我的网站上唱歌时,我设置了一个布尔类型的变量 true。我的 canActivate 使用这个变量。但是如果我刷新页面,值 return 为 false。如果页面刷新

,我需要维护该值

代码

export class AuthService{
   loggedin = false;

   isAuthenticated(){
     return this.loggedin;
   }

   login(){
     this.loggedin = true;
   }

   logout(){
     this.loggedin = false;
   }
}

并且可以激活

@Injectable()
export class AuthGuard implements CanActivate{

   constructor(private authService: AuthService, private router: Router){}

   canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): Observable<boolean> | Promise<boolean> | boolean{
     if(this.authService.isAuthenticated()){
       return true;
     }else{
       this.router.navigate(['/']);
     }
   }
}

当我进行登录时,我调用函数登录并将值设置为 true。但如果我重新加载页面,该值将重置为 false。我需要在价值中实现真实。更改值的一种方法是调用注销方法。为什么我可以这样做?

使用 localStorage,这是您重构的方法,应该可以正常工作:

   isAuthenticated(){
     return localStorage.getItem('loggedin', true);
   }

   login(){
     localStorage.setItem('loggedin', true);
   }

   logout(){
     localStorage.removeItem('loggedin'); // here you can either remove the item or use setItem and simply assign a false value localStorage.setItem('loggedin', false);
   }

现在,当您刷新时,您的应用程序将检查 isAuthenticated(),后者将检查值的存储。

如果使用localStorage.setItem(),会出现bug,重启浏览器变量还在,可能是用户登录信息,这是不能接受的。 使用window.sessionStorage["xxx"]是一个更好的方法,这使得变量只在一个会话中有效,如果重启浏览器,变量就失效了,这样更可能是常见的情况。