Necesito un temporizador en Angular 2, que marque después de un intervalo de tiempo y realice alguna tarea (puede llamar a algunas funciones).
¿Cómo hacer esto con Angular 2?
Además de todas las respuestas anteriores, lo haría usando RxJS Observables
por favor revise Observable.timer
Aquí hay un código de muestra, comenzará después de 2 segundos y luego marcará cada segundo:
import {Component} from 'angular2/core'; import {Observable} from 'rxjs/Rx'; @Component({ selector: 'my-app', template: 'Ticks (every second) : {{ticks}}' }) export class AppComponent { ticks =0; ngOnInit(){ let timer = Observable.timer(2000,1000); timer.subscribe(t=>this.ticks = t); } }Y aquí hay un plunker que funciona.
Actualizar Si desea llamar a una función declarada en la clase AppComponent, puede realizar una de las siguientes acciones:
** Suponiendo que la función a la que desea llamar se llame func ,
ngOnInit(){ let timer = Observable.timer(2000,1000); timer.subscribe(this.func); }El problema con el enfoque anterior es que si llama a 'esto' dentro de func, se referirá al objeto del suscriptor en lugar del objeto AppComponent, que probablemente no sea lo que desea.
Sin embargo, en el siguiente enfoque, crea una expresión lambda y llama a la función func dentro de ella. De esta manera, la llamada a func todavía está dentro del alcance de AppComponent. Esta es la mejor manera de hacerlo en mi opinión.
ngOnInit(){ let timer = Observable.timer(2000,1000); timer.subscribe(t=> { this.func(t); }); }verifique este plunker para ver el código de trabajo.
Otra solución es usar TimerObservable
TimerObservable es una subclase de Observable.
import {Component, OnInit, OnDestroy} from '@angular/core'; import {Subscription} from "rxjs"; import {TimerObservable} from "rxjs/observable/TimerObservable"; @Component({ selector: 'app-component', template: '{{tick}}', }) export class Component implements OnInit, OnDestroy { private tick: string; private subscription: Subscription; constructor() { } ngOnInit() { let timer = TimerObservable.create(2000, 1000); this.subscription = timer.subscribe(t => { this.tick = t; }); } ngOnDestroy() { this.subscription.unsubscribe(); } }PD: No olvides darte de baja.
import {Component, View, OnInit, OnDestroy} from "angular2/core"; import { Observable, Subscription } from 'rxjs/Rx'; @Component({ }) export class NewContactComponent implements OnInit, OnDestroy { ticks = 0; private timer; // Subscription object private sub: Subscription; ngOnInit() { this.timer = Observable.timer(2000,5000); // subscribing to a observable returns a subscription object this.sub = this.timer.subscribe(t => this.tickerFunc(t)); } tickerFunc(tick){ console.log(this); this.ticks = tick } ngOnDestroy(){ console.log("Destroy timer"); // unsubscribe here this.sub.unsubscribe(); } }