调用或取消定时器事件角度2

时间:2017-02-21 16:44:43

标签: angular rxjs observable

我基本上有一个应该订阅commModel.sessionState$的类,如果isValid为真,它应该取消定时器并再次重新创建它。问题是,当计时器触发时,我收到此错误:TypeError: Cannot read property 'setSessionState' of undefined,但是在构造函数commModel中调试时可以。此外,订阅中的console.log不会执行。问题在哪里,我该如何解决?

import { Injectable } from '@angular/core';
import { CommonModel } from '../core/store/common.model';
import { Observable } from 'rxjs/Observable';

import 'rxjs/add/observable/interval';
import 'rxjs/add/operator/publish';
import 'rxjs/add/operator/startWith';

@Injectable()
export class SessionTimeoutHandler {

  sessionState: Observable<boolean>;
  timeoutCountdown$: Observable<boolean>;

  timer: any;

  constructor(private commModel: CommonModel) {
    this.sessionState = commModel.sessionState$;
    this.sessionState.subscribe(
      isValid => {
        console.log('test',isValid);
        if(isValid) {
          clearTimeout(this.timer);
          this.timer = setTimeout(this.invalidateSessionState, 5 * 1000);
        }
      }
    )

    this.timer = setTimeout(this.invalidateSessionState, 5 * 1000);
  }

  invalidateSessionState() {
    this.commModel.setSessionState(false);
  }

}

1 个答案:

答案 0 :(得分:3)

this需要特别注意使用bind

this.timer = setTimeout(this.invalidateSessionState.bind(this), 5 * 1000);

或箭头功能

this.timer = setTimeout(() => this.invalidateSessionState(), 5 * 1000);