Angular 2のタイマーが必要です。タイマーが時間間隔の後に作動し、いくつかのタスクを実行します(いくつかの関数を呼び出す場合があります)。
Angular 2でこれを行う方法は?
Angular 2のタイマーが必要です。タイマーが時間間隔の後に作動し、いくつかのタスクを実行します(いくつかの関数を呼び出す場合があります)。
Angular 2でこれを行う方法は?
回答:
以前のすべての答えに加えて、RxJS Observablesを使用してそれを行います
Observable.timerを確認してください
以下はサンプルコードで、2秒後に開始し、1秒ごとにティックします。
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);
}
}
そして、ここに働くプランカーがあります
更新 AppComponentクラスで宣言された関数を呼び出す場合は、次のいずれかを実行できます。
**呼び出したい関数の名前がfuncであると仮定すると、
ngOnInit(){
let timer = Observable.timer(2000,1000);
timer.subscribe(this.func);
}
上記のアプローチの問題は、func内で 'this'を呼び出す場合、AppComponentオブジェクトではなく、サブスクライバーオブジェクトを参照することです。
ただし、以下のアプローチでは、ラムダ式を作成し、その内部で関数funcを呼び出します。このようにして、funcの呼び出しはまだAppComponentのスコープ内にあります。これは私の意見ではそれを行うための最良の方法です。
ngOnInit(){
let timer = Observable.timer(2000,1000);
timer.subscribe(t=> {
this.func(t);
});
}
動作するコードについては、このプランカーを確認してください。
timer使用しているようsetInterval()です。ただし、デフォルトのスケジューラーの代わりに使用するanimationFrameスケジューラー(を使用requestAnimationFrame())を渡すことができますasync。あなたがする必要があるのはObservable.timer(*,*,Scheduler.animationFrame)、与えられたです。import {Scheduler} from ‘rxjs’しかし、それではうまくtimerいかないようです。まだ使っているようsetInterVal()です。ただし、などの他の種類のオブザーバブルObservable.range(0,1000,Scheduler.animationFrame)では、requestAnimationFrameが確実に使用されます。パフォーマンスに関しては、現時点では確かに答えることはできません。
別の解決策は、TimerObservableを使用することです
TimerObservableは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();
}
}
PS:登録を解除することを忘れないでください。
this.subscription.unsubscribe();解除中に呼び出されます:サブスクライブ解除。
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();
}
}
rxjs 6.2.2とAngular 6.1.7で、私は次のものを得ていました:
Observable.timer is not a function
エラー。これは、に置き換えることで解決しましObservable.timerたtimer。
import { timer, Subscription } from 'rxjs';
private myTimerSub: Subscription;
ngOnInit(){
const ti = timer(2000,1000);
this.myTimerSub = ti.subscribe(t => {
console.log("Tick");
});
}
ngOnDestroy() {
this.myTimerSub.unsubscribe();
}
タイマーを使わなければならないという問題に直面しましたが、2つのコンポーネントを同じ画面に同時に表示する必要がありました。サービスにtimerObservableを作成しました。両方のコンポーネントでタイマーをサブスクライブしましたが、どうなったのですか?同期されません。新しいサブスクリプションは常に独自のストリームを作成するためです。
私が言いたいのは、1つのタイマーを複数の場所で使用する場合、常に.publishReplay(1).refCount()
オブザーバーの最後に置くと、毎回同じストリームが公開されるためです。
例:
this.startDateTimer = Observable.combineLatest(this.timer, this.startDate$, (localTimer, startDate) => {
return this.calculateTime(startDate);
}).publishReplay(1).refCount();
RxJSをサービスとして使用してこれを容易にするnpmパッケージを見つけました。
https://www.npmjs.com/package/ng2-simple-timer
同じコンポーネントで何度も使用している場合でも、既存のタイマーを「サブスクライブ」してバジリオンタイマーを作成する必要はありません。
ngOnInitでメソッドを実行する場合は、次のようにすることができます。
RXJSからこの2つのライブラリをインポートします。
import {Observable} from 'rxjs/Rx';
import {Subscription} from "rxjs";
次に、タイマーとプライベートサブスクリプションを宣言します。例:
timer= Observable.timer(1000,1000); // 1 second for 2 seconds (2000,1000) etc
private subscription: Subscription;
タイマーが停止したときにメソッドを最後に実行します
ngOnInit() {
this.subscription = this.timer.subscribe(ticks=> {
this.populatecombobox(); //example calling a method that populates a combobox
this.subscription.unsubscribe(); //you need to unsubscribe or it will run infinite times
});
}
これですべてです、Angular 5
Set Timer and auto call service after certain time
// Initialize from ngInit
ngOnInit(): void {this.getNotifications();}
getNotifications() {
setInterval(() => {this.getNewNotifications();
}, 60000); // 60000 milliseconds interval
}
getNewNotifications() {
this.notifyService.getNewNotifications().subscribe(
data => { // call back },
error => { },
);
}