我正在使用localStorage在刷新和在页面之间移动时保持用户数据和令牌的活动。我希望当用户关闭浏览器页面时,localStorage清除所有数据。我正在使用ngOnDestroy和HostListener,但是它们都不起作用。 这是我的代码:
编辑:我试图用sessionStorage替换localStorage,但是它也不起作用。我更新了以下代码
app.component.ts
export class AppComponent {
private authUserService: AuthUserService
// clear sessions after windows is closed
@HostListener('window:beforeunload', ['$event'])
beforeunloadHandler(event) {
this.authUserService.logout();
}
ngOnDestroy () {
this.authUserService.logout();
}
}
auth-user.service.ts
import { Injectable, OnDestroy } from '@angular/core';
import { BehaviorSubject } from 'rxjs';
import { Observable, throwError } from 'rxjs';
import { LocalStorage } from '@ngx-pwa/local-storage';
import { SessionStorage } from 'sessionstorage';
export class AuthUserService implements OnDestroy {
private user: IUser;
public errorMessage: string;
isLoginSubject = new BehaviorSubject<boolean>(this.hasToken());
constructor(private userService: UserService) { }
// store the session and call http get
login(id: number) {
this.userService.getUser(id).subscribe(
user => {
this.user = user;
localStorage.setItem('user', JSON.stringify(this.user));
sessionStorage.setItem('token', 'JWT');
this.isLoginSubject.next(true);
},
error => this.errorMessage = <any>error
);
}
// if we have token the user is loggedIn
// @returns {boolean}
private hasToken() : boolean {
return !!localStorage.getItem('token');
}
// @returns {Observable<T>}
isLoggedIn() : Observable<boolean> {
return this.isLoginSubject.asObservable();
}
logout() {
localStorage.removeItem('user');
sessionStorage.removeItem('token');
this.isLoginSubject.next(false);
}
ngOnDestroy() {
this.logout();
}
}