我在登录时将身份验证令牌设置在本地存储中,并在注销时清除它。但是,在注销后,如果用户尝试再次登录,则会使用缓存中获取的旧身份验证令牌而不是新设置的值。如何在清除本地存储时清除缓存。我的应用程序中使用了Angular 2。
登录:
localstorage.setItem("token", "value")
退出登录:
localstorage.clear();
我在登录时将身份验证令牌设置在本地存储中,并在注销时清除它。但是,在注销后,如果用户尝试再次登录,则会使用缓存中获取的旧身份验证令牌而不是新设置的值。如何在清除本地存储时清除缓存。我的应用程序中使用了Angular 2。
登录:
localstorage.setItem("token", "value")
退出登录:
localstorage.clear();
在执行 localstorage.clear(); 前,你需要移除元素;为此,你的代码应该像这样:
localStorage.removeItem('Token');
localstorage.clear();
请注意,如果你正在使用 BehaviorSubject,你还需要将其设置为 null;假设如下:
private loggedInUserSubject: BehaviorSubject<User>;
public loggedInUser: Observable<User>;
and in the constructor, to get the user's value:
this.loggedInUserSubject= new BehaviorSubject<User>(JSON.parse(localStorage.getItem('loggedInUser')));
this.loggedInUser= this.loggedInUserSubject.asObservable();
localStorage.removeItem('currentUser');
this.currentUserSubject.next(null);
localstorage.clear();
你怎么这么有信心用户会注销?
如果用户只是关闭了浏览器怎么办?
我建议除了安全令牌之外,还保存一个时间戳
并为凭据设置超时时间。
localStorage['token_time'] = ''+myDate.getTime();
// And to restore it :
var myDate = new Date(parseInt(localStorage['token_time'], 10));