【发布时间】:2021-07-30 13:21:59
【问题描述】:
我被一个问题困住了,这花了我好几天的时间,但还没有预期的结果。我有一个登录组件和身份验证服务。当我登录时,计时器在 30 秒后开始弹出一个模式,再过 30 秒后它会退出。登录后,如果我在弹出窗口之前退出并再次登录,仍然会出现之前的弹出窗口。请帮助解决这个问题。提前致谢。
login.component.ts
public async login(form: NgForm, event: Event) {
this.auth.login(form.value.username, form.value.password).toPromise();
}
auth.service.ts
private count: number = 0;
private timerSubscription: Subscription = new Subscription();
private timer: Observable<number>;
private timeoutExpired: Subject<number> = new Subject<number>();
popupInterval: any;
timeLeft: number = 30;
constructor(
private router: Router,
private notification: NotificationService
) { }
.
.
.
public startTimer(timeoutInMilliseconds: number) {
if (!this.timerSubscription.closed) {
this.timerSubscription.unsubscribe();
}
this.timer = Observable.timer(timeoutInMilliseconds);
this.timerSubscription = this.timer.subscribe(n => {
this.timeoutExpired.next(++this.count);
});
}
.
.
.
public login(userid: string, password: string): Observable<boolean> {
return this.api.post('/auth/login', {
username: userid,
password: password
}, JsonApiService.HeaderJson).map((response: JsonResponse) => {
if (this.timerSubscription.closed) {
this.timerSubscription = new Subscription();
}
const currentDate = new Date();
const token: Token = TypedJSON.parse(JSON.stringify(response.json),
Token);
// notify user about the end of the session which ends in five minutes
this.startTimer(token.expirationDate.getTime() - currentDate.getTime() - 30000);
this.timerSubscription = this.timeoutExpired.subscribe(n => {
let popupInterval = setInterval(() => {
if(this.timeLeft == 0) {
this.notification.dialog.closeAll();
this.logout();
} else {
this.timeLeft--;
}
},1000)
this.notification.notificationOkOnly(
'Session Timeout',
'Your session will expire in 1 minutes. Please finish your work in time.'
)
});
return true;
}).catch((err) => {
{
this.notification.notificationOkOnly('Login failed', 'login failed ');
}
return Observable.of(false)
}).share();
}
.
.
.
public logout(): void {
if (!this.timerSubscription.closed) {
this.timerSubscription.unsubscribe();
}
clearInterval(this.popupInterval)
Token.RemoveToken();
this.router.navigateByUrl('/auth/login');
}
【问题讨论】:
标签: angular typescript setinterval router