user3719857
user3719857

Reputation: 1123

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

}

Upvotes: 3

Views: 3119

Answers (1)

G&#252;nter Z&#246;chbauer
G&#252;nter Z&#246;chbauer

Reputation: 658037

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

Upvotes: 3

Related Questions