3

I basically have a class that should subscribe to commModel.sessionState$ and if isValid is true it should cancel the timer and recreate it again. The problem is that when the timer fires I get this error: TypeError: Cannot read property 'setSessionState' of undefined, but when debugging in the constructor commModel is OK. Also the console.log in the subscribe does not execute. Where is the problem and how can I fix it ?

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

}
user3719857
  • 1,083
  • 4
  • 16
  • 45

1 Answers1

3

this needs some special attention by using bind:

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

or arrow functions

this.timer = setTimeout(() => this.invalidateSessionState(), 5 * 1000);
Günter Zöchbauer
  • 623,577
  • 216
  • 2,003
  • 1,567