I would like to have a timer that would fire logout()
in my authentication.service
at a specific time automatically no matter on which page I am in my application.
I tried creating a timer on my AuthenticationService
but the problem is that if I redirect to another page.. this timer is lost.
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']);
}
}
I thought about creating timer on app.component but then I want to subscribe to the timer only when login function of authentication service is called from login form.