我正在使用rxjs/Rx中的角2创建一个时钟,并使圈和斯普林特时间圈从它。代码块如下:
HTML: (app.component.html)
<div class="row">
<div class="col-xs-5">
<div class="row">
<div class="col-xs-6">
<h2>Lap Time</h2>
<ul *ngFor="let lTime of lapTimes">
<li>{{lTime}}</li>
</ul>
</div>
<div class="col-xs-6">
<h2>Sprint Time</h2>
<ul *ngFor="let sTime of sprintTimes">
<li>{{sTime}}</li>
</ul>
</div>
</div>
</div>
<div class="col-xs-5">
<h1>Current Time: {{timeNow}}</h1>
<div>
<button type="button" class="btn btn-large btn-block btn-default" (click)="onStart()">Start Timer</button>
<button type="button" class="btn btn-large btn-block btn-default" (click)="onLoop()">Sprint and Lap</button>
<button type="button" class="btn btn-large btn-block btn-default" (click)="onStop()">Stop Timer</button>
</div>
</div>
</div>TypeScript: (app.component.ts)
import { Component } from '@angular/core';
import { Observable, Subscription } from 'rxjs/Rx';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
sprintTimes: number[] = [0];
lapTimes: number[] = [0];
timeNow: number = 0;
timer: Observable<any> = Observable.timer(0, 1000);
subs: Subscription;
onStart () {
this.subs = this.timer.subscribe((value) => {
this.tickerFunc();
});
// this.onLoop();
}
onLoop () {
this.onLap();
this.onSprint();
}
onSprint () {
this.sprintTimes.push(this.timeNow);
}
onLap () {
this.lapTimes.push(this.timeNow - this.sprintTimes[this.sprintTimes.length - 1]);
}
onStop () {
this.subs.unsubscribe();
}
tickerFunc () {
this.timeNow++;
}
}这允许我创建一个时钟功能。但是,Rxjs/Rx没有被足够的文档化(我很难仅通过它的文档来理解它)。
有什么更好的方法来做我在这里做的工作吗?(我在这里的主要目的是:我想进行在线考试/模拟考试。)
当我按两次开始时钟按钮时,我的时钟滴答的速度是原来的两倍。(我不明白这种行为)
还有其他的第三部分工具可以让这更容易吗?
对不起,我的Type脚本代码没有正确显示,我发现很难使用文本编辑器。而且这里也不是做家庭作业的地方。
发布于 2017-08-17 09:12:49
当我按两次开始时钟按钮时,我的时钟滴答的速度是原来的两倍。(我不明白这种行为)
当您单击此按钮时,您将执行以下代码:
this.subs = this.timer.subscribe((value) => {
this.tickerFunc();
});因此,每次单击该按钮时,都启动一个新计时器,每次计时器发出事件(即每一秒),就执行
tickerFunc () {
this.timeNow++;
}因此,如果单击该按钮一次,则每次计时器发出时,即每秒钟增加一次this.timeNow。
如果第二次单击它,则每次第一个计时器发出和第二个计时器发出时都会增加它。所以每秒两次。
似乎你只是不应该启动一个计时器,如果它已经开始。因此,如果计时器已经启动,请禁用该按钮。
发布于 2017-08-17 11:31:42
您必须调用取消订阅来停止前一个计时器。
onStart () {
if (this.subs) {
this.subs.unsubscribe(); // Stop previous timer
}
this.subs = this.timer.subscribe((value) => {
this.tickerFunc();
});
// this.onLoop();
}https://stackoverflow.com/questions/45730832
复制相似问题