如何在Angular中的应用程序级别创建全局计时器?

时间:2018-05-11 07:19:00

标签: angular typescript rxjs angular5

我想有一个计时器,无论我在我的申请中的哪个页面,都会在特定时间自动触发logout() authentication.service

我尝试在我的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上创建计时器但是我只想在从登录表单调用身份验证服务的登录功能时才订阅计时器。

1 个答案:

答案 0 :(得分:0)

我通过创建:

解决了这个问题

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;
        }
  }
}

<强> authentication.service

 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},...
    ...
    ...