【问题标题】:How to create a global timer on application level in Angular?如何在 Angular 中创建应用程序级别的全局计时器?
【发布时间】: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


【解决方案1】:

您可以在登录时将计算的注销时间存储在localStorage中,然后在构造函数中您可以从localStorage时间或您的默认值启动计时器。

@Injectable()
export class AuthenticationService {
  ticks =0;
  timer :Observable<number>;

  constructor(private http: Http, private _JwtHelper: JwtHelper, private router: Router) {
    const logoutTime = localStorage.getItem('logoutTime') || Date.now() + 7000;
    this.startTimer(logoutTime);
  }

  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);
          localStorage.setItem('logoutTime', Date.now() + 7000);
          this.startTimer(Date.now() + 7000);
          return true;
        }
        return false;
      });
  }

  startTimer(time) {
    this.timer = Observable.timer(time);
    this.timer.subscribe(t=> {
      this.func(this);
    });
  }

  func(t){
      this.logout();
      t.unsubscribe();
  }

  logout(): void {

    localStorage.removeItem('token');
    localStorage.removeItem('logoutTime');
    this.router.navigate(['/login']);

  }

}

【讨论】:

  • 这就是我正在做的事情,问题是一旦我重定向到任何其他页面,计时器就会丢失。
【解决方案2】:

我通过创建解决了它:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-04-30
    • 1970-01-01
    • 2011-06-19
    • 2022-12-18
    相关资源
    最近更新 更多