我基本上有一个应该订阅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);
}
}
答案 0 :(得分:3)
this
需要特别注意使用bind
:
this.timer = setTimeout(this.invalidateSessionState.bind(this), 5 * 1000);
或箭头功能
this.timer = setTimeout(() => this.invalidateSessionState(), 5 * 1000);