Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Call or cancel timer event angular 2

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

}
like image 282
user3719857 Avatar asked Jul 14 '26 22:07

user3719857


1 Answers

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);
like image 55
Günter Zöchbauer Avatar answered Jul 16 '26 13:07

Günter Zöchbauer