Is there a way to implement a timer that will automatically execute the logout()
function in my authentication.service
at a specific time, regardless of which page I am currently on within my application?
I attempted to create a timer within my AuthenticationService
, but encountered an issue where the timer would be lost if I redirected to another page.
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 considered implementing the timer within app.component, but I only want to subscribe to the timer when the login function of the authentication service is called from the login form.