【发布时间】:2018-10-21 13:24:06
【问题描述】:
我想要一个计时器,无论我在应用程序的哪个页面上,它都会在特定时间自动触发我的authentication.service 中的logout()。
我尝试在我的AuthenticationService 上创建一个计时器,但问题是如果我重定向到另一个页面......这个计时器就会丢失。
authentication.service:
@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 上创建计时器,但我想仅在从登录表单调用身份验证服务的登录功能时订阅计时器。
【问题讨论】:
-
创建一个 Timer 服务并在所有 Component 页面中注入这样的服务怎么样?
-
您可以在
AuthenticationService中创建计时器并让它运行。然后在调用login时,您只需订阅它。 -
您需要“计时器”始终在您的应用程序中。两个选项:1.- 应用程序组件,2.- 拥有所有您的组件的服务
-
@martin 我试过了。没用。
-
@Eliseo 我尝试从登录组件调用设置计时器的 appcomponent 函数,但我仍然面临同样的问题。一旦我将它重定向到其他页面,计时器就会丢失。
标签: angular typescript rxjs angular5