我的应用程序中运行了两个计时器。当我单击按钮时,timer2应该从10秒开始,但是我的timer2仅继续执行我的timer1。
我尝试了退订,但似乎没有用。任何帮助将不胜感激。
app.component.ts
import { Component } from '@angular/core';
import { timer } from 'rxjs';
import { filter, takeWhile } from 'rxjs/operators';
import { CountdownService } from './countdown.service'
@Component({
selector: 'my-app',
templateUrl: './app.component.html',
styleUrls: [ './app.component.css' ]
})
export class AppComponent {
value1: string | number;
value2: string | number;
constructor( private countdownService: CountdownService) {
// countdown is started
countdownService.start(10);
// first subscriber subscribes
countdownService.countdown().subscribe(
t => {
this.value1 = t
},
null,
() => this.value1 = 'Done!'
);
}
newTimer() {
this.countdownService.start(10);
this.countdownService.countdown().subscribe(
t => this.value2 = t,
null,
() => this.value2 = 'Done!'
);
}
}
服务
import { Injectable } from '@angular/core';
import { timer, Subject, Observable } from 'rxjs';
import { takeWhile, map } from 'rxjs/operators';
@Injectable()
export class CountdownService {
private _countdown = new Subject<number>();
countdown(): Observable<number> {
return this._countdown.asObservable();
}
private isCounting = false;
start(count: number): void {
// Ensure that only one timer is in progress at any given time.
if (!this.isCounting) {
this.isCounting = true;
timer(0, 1000).pipe(
takeWhile(t => t < count),
map(t => count - t)
).subscribe(
t => this._countdown.next(t),
null,
() => {
this._countdown.complete();
this.isCounting = false;
// Reset the countdown Subject so that a
// countdown can be performed more than once.
this._countdown = new Subject<number>();
}
);
}
}
}
html
<h1>{{ value1 }}</h1>
<h1>{{ value2 }}</h1>
<div>
<button (click)="newTimer()" class="btn btn-link btn-sm">New</button>
</div>
当我的计时器2启动时,计时器1应该停止,而计时器2应该在10秒后开始 这是我找到并修改的内容,但没有运气。
https://stackblitz.com/edit/angular-sexrqx?file=src%2Fapp%2Fapp.component.html