2

Quiero hacer un contador de tiempo. Y que al presionar un botón se reinicie. Para ello estoy usando Angular 7 y el operador timer de RxJS.

import { Component } from '@angular/core';
import { timer } from 'rxjs';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  tiempo = 0;

  constructor() {
    timer(0, 1000).subscribe(t => this.tiempo = t);
  }
}

¿Cómo puedo reiniciar el operador timer?

2 respuestas 2

2

Puede hacer algo como esto:

  inscribir: any;

  onComenzar() {
    const source = timer(0, 1000);
    this.inscribir = source.subscribe(val => this.tiempo = val);
  }

  onDetener() {
    this.inscribir.unsubscribe();
  }

En la vista podrías tener algo así para los eventos de Comenzar y Detener el Timer:

  <h2> tiempo: {{ tiempo }}</h2>
  <button (click)="onComenzar()">Comenzar Timer</button>
  <button (click)="onDetener()">Detener Timer</button>
1
  • Sí, de hecho fue la manera en que lo hice, aunque para reiniciarlo, además del .unsubscribe, me volví a subscribir para que el timer empezará de nuevo. el 15 nov. 2018 a las 6:07
0

Lo puedes hacer con Subject y switchMap

private reiniciar$: Subject<void>;
tiempo = 0;

constructor() {
    this.reiniciar$ = new Subject<void>();
    this.reiniciar$
        .asObservable()
        .pipe(
            startWith(null),
            switchMap(() => timer(0, 1000))
        )
        .subscribe(t => this.tiempo = t);
}

reiniciar() {
    this.reiniciar$.next();
}

Tu Respuesta

By clicking “Publica tu respuesta”, you agree to our terms of service and acknowledge you have read our privacy policy.

¿No es la respuesta que buscas? Examina otras preguntas con la etiqueta o formula tu propia pregunta.