我在angularjs应用程序中实现了一个计时器功能,如下所示:
$timeout($scope.startFilling, 30000)
$scope.onTimeout = function(){
$scope.counter1--; <= counter1 is initialized to 3
mytimeout = $timeout($scope.onTimeout,1000);
if($scope.counter1==0){
$timeout.cancel(mytimeout);
$scope.counter1=0
}
}
var mytimeout = $timeout($scope.onTimeout,1000);
我基本上在30秒后调用一个函数,计数器从30变为0,在0时我取消了计时器。
我尝试在angular2中实现它,如下所示:
start(){
let timer = Observable.timer(3000,1000);
this.myCounter = timer.subscribe(t=> this.startFilling(t));
}
startFilling(counter){
this.counter1=--counter;
if(this.counter1==0){
this.myCounter.unsubscribe();
}
}
但这并非完全正确。我在我的模板上绑定counter1(初始化为3)。 start()
函数被称为按钮单击,一旦调用它,我想将counter1从3减少到0,在3秒后我想调用startFilling()
函数。我该怎么做?
答案 0 :(得分:1)
从计数器中减去一个,当它达到0时取消订阅:
tickerFunc(tick){
this.counter1 = this.counter1 - 1;
if(this.counter1==0){
this.counter.unsubscribe();
}
}
答案 1 :(得分:0)
计数器基于0,因此您将counter1设置为-1然后设置为0.每次订阅时,将counter1减1可能更容易。