Search code examples
angulartimerrxjs

Angular TimerObervable doesn't see component field?


This is my TS file for my component:

import { Component, OnInit } from '@angular/core';
import {TimerObservable} from "rxjs/observable/TimerObservable";

@Component({
  selector: 'app-dashboard',
  templateUrl: './dashboard.component.html',
  styleUrls: ['./dashboard.component.css']
})
export class DashboardComponent implements OnInit {

  userWarn = true;
  constructor() { }

  ngOnInit() {
    let timer = TimerObservable.create(0, 1000);
    timer.subscribe(this.fun);

  }

  fun(t){
    if(t === 10)
      this.userWarn = false;

    console.log(t);
    console.log('userWarn: ' + this.userWarn);
  }

}

The timer starts out, and keep counting but when it logs the userWarn to the console it shows "undefined" for t<10s. When I log userWarn to the console in the ngOnInit method, it logs "true", so I guess the task that periodically performs the fun function doesn't see the userWarn from the component? But I don't know what to do for this the work I want it to. I need this because I have a html tag binded to the userWarn.

<div class="warning-log" *ngIf="userWarn" ><h1>Potwierdź obecność!</h1></div>

Solution

  • It's because you have to use "wrapper" function inside subscribe(), like this:

    timer.subscribe(d => this.fun(d));
    

    And here is a live example: STACKBLITZ