我想创建一个独立的服务,只负责检查令牌是否过期。angular2 - 设置间隔来检查jwt令牌的有效性
通常我会开始一个间隔并使用tokenNotExpired()
或JwtHelper.isTokenExpired()
来测试JWT令牌。但是对于Angular2,我不太确定我是如何处理这种东西的。这不是那么容易,对吧? :)
所有的标记有效性目前正在home.component中执行,但这正是我想要避免的,因此打算将这个问题分解为独立的服务。
下面只是一个假设的例子,它可能如何工作。
- 用户登录,在
- 家组件初始化
- 订阅会话check.service.validate()
- 检查会话验证检查
这里的问题的输出是,我应该使用Observable还是刚开始一个简单的间隔?处理组件内的定期调用的最佳和最恰当的概念是什么?
home.component.ts
import { Component, OnInit } from '@angular/core';
import { Http } from '@angular/http';
import { Router } from '@angular/router';
import { SessionCheckService } from '../services/session-check.service';
@Component({
moduleId: module.id,
selector: 'home',
templateUrl: '../templates/home.component.html',
styleUrls: [ '../styles/home.component.css' ],
providers: [ SessionCheckService ]
})
export class HomeComponent implements OnInit {
private jwt: string;
private decodedJwt: string;
constructor (
private router: Router,
private http: Http
private sessionCheckService: SessionCheckService
// private jwtHelper: JwtHelper
) {}
ngOnInit(): void {
this.jwt = localStorage.getItem('id_token');
// this.decodedJwt = null; //this.jwt && this.jwtHelper.decodeToken(this.jwt);
var s = this.sessionCheckService.validate(this.jwt);
s.subscribe((res) => {
console.log(res)
})
}
public logout() {
localStorage.removeItem('id_token');
this.router.navigate(['login']);
}
}
会话check.service.ts
import { JwtHelper } from 'angular2-jwt';
import { Injectable } from '@angular/core';
//import { AuthHttp, JwtHelper } from 'angular2-jwt';
import { Observable } from 'rxjs';
import 'rxjs/add/operator/toPromise';
@Injectable()
export class SessionCheckService {
constructor(private jwtH: JwtHelper){};
validate(token:string): Observable<boolean>{
return new Observable.interval(500).flatMap(() => {
this.jwtH.isTokenExpired(token)
});
}
}
请看看:angular2-jwt(https://github.com/auth0/angular2-jwt) – MMK
当用户试图打开'/ home'路由时,我已经检查过令牌。但我的意图是在整个生命周期中定期检查令牌。 – Alexus