Как сбросить номер с Observable Subject для запуска нового таймера? - PullRequest
0 голосов
/ 11 апреля 2019

У меня есть два таймера, которые запускаются в моем приложении. Таймер2 должен начинаться с 10 секунд, когда я нажимаю кнопку, но мой таймер2 только продолжает мой таймер1.

Я пытался отписаться, но, похоже, это не работает. Любая помощь будет высоко ценится.

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

...