angular - 如何在 Angular 中创建应用程序级别的全局计时器?
问题描述
我希望有一个计时器,无论我在我的应用程序中的哪个页面上,它都会在特定时间自动logout()
触发。authentication.service
我尝试在我的身上创建一个计时器,AuthenticationService
但问题是如果我重定向到另一个页面..这个计时器就会丢失。
身份验证服务:
@Injectable()
export class AuthenticationService {
ticks =0;
timer :Observable<number>;
constructor(private http: Http, private _JwtHelper: JwtHelper, private router: Router) {
}
isLoggedIn() {
console.log('authentication service islogged in called ')
let token = localStorage.getItem('token');
if (!token) { return false; }
else {
return true;
}
}
login(credentials) {
return this.http.post('http://somthing/api/login/login',
credentials)
.map(response => {
let result = response.json();
if (result && result.token) {
localStorage.setItem('token', result.token);
this.timer = Observable.timer(7000,1000);
this.timer.subscribe(t=> {
this.func(this);
});
return true;
}
return false;
});
}
func(t){
this.logout();
t.unsubscribe();
}
logout(): void {
localStorage.removeItem('token');
this.router.navigate(['/login']);
}
}
我考虑过在 app.component 上创建计时器,但是我只想在从登录表单调用身份验证服务的登录功能时订阅计时器。
解决方案
我通过创建解决了它:
CanActivateViaAuthGuard.service
@Injectable()
export class CanActivateViaAuthGuard implements CanActivate {
constructor(private authService: AuthenticationService, private router: Router) {}
canActivate() {
if(this.authService.isLoggedIn()==false ){
this.router.navigate(['/login']);
return false;
}
else{
return true;
}
}
}
身份验证服务:
isLoggedIn() {
let token = localStorage.getItem('token');
if (!token) { return false; }
else {
this.setTimeOutTimer();
return true;
}
}
setTimeOutTimer() {
console.log('**setTimeOutTimer**')
if(this.sub){
this.sub.unsubscribe();
}
let expiry=this.currentUser.exp;
this.timer = Observable.timer(1000, 1000);
this.sub = this.timer.subscribe(t => {
let timenow= moment().format('X');
console.log(expiry + ' '+timenow );
if(expiry<timenow){
this.sub.unsubscribe();
this.logout();
}
});
}
get currentUser() {
let token = localStorage.getItem('token');
if (!token) return null;
return this._JwtHelper.decodeToken(token);
}
路线:
const routes: Routes = [
{path: '', canActivate:[CanActivateViaAuthGuard], children:[
{path:'home', component: HomeComponent},//,canActivate:[CanActivateViaAuthGuard]
{path:'dummy', component: DummyComponent},...
...
...
推荐阅读
- html - 背景网址不显示
- python - 我有一个文本文件(12 列和 10K 行)。我想从文本文件加载数据并馈送到二维数组
- html - 提供索引文件而不是下载提示
- javascript - 项目完成后,如何停止其中一个计数计时器(例如 countup2)并显示完成前的经过时间?
- python - 从 R 和 Python 发送电子邮件:535 5.7.3 身份验证不成功
- ios - 重复 iphone 提醒应用程序中的事件
- database - 在数据库中查找类似的文件/记录
- regex - 搜索大写或小写单词并返回大写或小写
- oracle - 尝试在表中插入一行并创建触发器后出现这些错误
- angular - 带有正文的Angular HttpClient Get方法