I have a set interval and I have created a custom timer, my view doesnt update


#1

import { Component } from ‘@angular/core’;

import { NavController } from ‘ionic-angular’;

@Component({
selector: ‘page-home’,
templateUrl: ‘home.html’
})
export class HomePage {
appname : string;
time : string;
timecolor : string;
constructor(public navCtrl: NavController) {
this.appname = “App Name”;
this.time = “02:00”;
this.timecolor = “primary”;
this.startTimer();
}

startTimer() {
let timer : any;
timer = this.time.split(":");
let minutes = parseInt(timer[0]);
let seconds = parseInt(timer[1]);
let refreshIntervalId = setInterval(function () {
if(seconds == 0){
minutes = minutes - 1;
seconds = 60;
if(minutes == 0){
clearInterval(refreshIntervalId);
}
}
seconds = seconds - 1;
this.time = minutes.toString() + “:” + seconds.toString();
console.log(this.time);
timer = timer - 1;
}, 1000);
}

}

this.time does not update in my view. But console.log shows time perfectly.


#2

Solved

import {Component, OnInit, OnDestroy} from ‘@angular/core’;
import { NavController } from ‘ionic-angular’;
import {Observable} from ‘rxjs/Rx’;

@Component({
selector: ‘page-home’,
templateUrl: ‘home.html’
})
export class HomePage implements OnInit {
appname : string;
time : string;
timecolor : string;
constructor(public navCtrl: NavController) {
this.appname = “App Name”;
this.time = “02:00”;
this.timecolor = “primary”;
}

ngOnInit(){
let timer1 : any;
timer1 = this.time.split(":");
let minutes = parseInt(timer1[0]);
let seconds = parseInt(timer1[1]);
let timer = Observable.timer(0,1000);
let subscription = timer.subscribe(t=>{
if(seconds == 0){
minutes = minutes - 1;
seconds = 60;
if(minutes == -1){
subscription.unsubscribe();
}
}
if(minutes != -1){
seconds = seconds - 1;
this.time = minutes.toString() + “:” + seconds.toString();
timer1 = timer1 - 1;
}
});
}

}