angular2でタイマーを作成する方法


95

Angular 2のタイマーが必要です。タイマーが時間間隔の後に作動し、いくつかのタスクを実行します(いくつかの関数を呼び出す場合があります)。

Angular 2でこれを行う方法は?


2
他の人が問題を再現できるようにするだけの十分なコードを含めます。これについては、最小、完全、検証可能な例を作成する方法をご覧ください。リンクできる問題の実際の例を作成できる場合(たとえば、sqlfiddle.comまたはjsbin.com上)は作成できますが、質問自体にコードも含めてください。誰もが外部サイトにアクセスできるわけではなく、リンクは時間の経過とともに壊れる可能性があります。
Prasad 2016年

15
これは実際には非常に役立つ質問です。オブザーバブルは学習して使用することが重要です。ユーザーがこの質問から進むためのコードを持っていなかったとしても、他の人に役立つでしょう。
Winnemucca

このコメントは同じバケットに分類されますが、前の2人はどちらも助けにならず、質問にコメントしただけです...どうやら、人々は現在、setTimeoutを再び使用しているようです。
rbnzdave

setTimeoutは本当に古い学校です-以下の新しいTimerObservableをチェックアウトしてください
フィリップ

2
let this._timer = setInterval(()=> this.getWidgetData()、10000); そして、clearInterval(this._timer);を必ず呼び出してください。破壊時
crh225 2016年

回答:


129

以前のすべての答えに加えて、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.subscribe(t => this.ticks = t);`に渡すことができますか?
kuntal 2016年

@matrixwebtechはい、 't => this.ticks = t'はラムダ式であり、 'function(t){this.ticks = t}'とまったく同じです
Abdulrahman Alsoghayer

timer.subscribe(function name(){console.log( "hhhhhh")});を試します。どのように機能しますが、ngOnInit()を個別に宣言した関数を呼び出す方法{let timer = Observable.timer(2000,1000); timer.subscribe(function(){this.fun();}); } fun(){console.log( "hhhhhh")}
kuntal 2016年

@matrixwebtechは、私の最新の回答の例を確認してください。
Abdulrahman Alsoghayer 2016年

1
@Notflip内部でtimer使用しているようsetInterval()です。ただし、デフォルトのスケジューラーの代わりに使用するanimationFrameスケジューラー(を使用requestAnimationFrame())を渡すことができますasync。あなたがする必要があるのはObservable.timer(*,*,Scheduler.animationFrame)、与えられたです。import {Scheduler} from ‘rxjs’しかし、それではうまくtimerいかないようです。まだ使っているようsetInterVal()です。ただし、などの他の種類のオブザーバブルObservable.range(0,1000,Scheduler.animationFrame)では、requestAnimationFrameが確実に使用されます。パフォーマンスに関しては、現時点では確かに答えることはできません。
Abdulrahman Alsoghayer 2017

79

別の解決策は、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:登録を解除することを忘れないでください。


3
購読解除の部分が重要です
Tucker

どうやって退会するの?そしていつ?
ミゲルスティーブンス

1
@Notflip ngOnDestroyは、コンポーネントの初期化this.subscription.unsubscribe();解除中に呼び出されます:サブスクライブ解除。
フィリップ

上記を参照せずにthis.subscriptionをどのように使用できますか?
Winnemucca 2017年

2
どのように一時停止して再起動しますか?
ダニ

11
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();

    }


}

3
これは、他の回答でまだ説明されていないものを追加しないのですか、それともそうですか?
ギュンターZöchbauer

5

rxjs 6.2.2とAngular 6.1.7で、私は次のものを得ていました:

Observable.timer is not a function

エラー。これは、に置き換えることで解決しましObservable.timertimer

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();    
}

3
サブスクリプションを解除するには、上記の@ alexis-pooのようなサブスクリプション変数が必要です。参照:stackoverflow.com/questions/40181169/…。これは、その点について書かれたように機能しないあなたの答えに基づいています。
リード

常にPostsを最新のAngularバージョンに更新しているこの人が大好きです...いつもAngularJSとAngularに非常に苦労しています。ありがとう!
chainstair

4

単純にsetIntervalユーティリティを使用し、コールバックとしてarrow関数を使用thisして、コンポーネントインスタンスを指すことができます。

例:

this.interval = setInterval( () => { 
    // call your functions like 
    this.getList();
    this.updateInfo();
});

ngOnDestroyライフサイクルフック内で、間隔をクリアします。

ngOnDestroy(){
    clearInterval(this.interval);
}

3

タイマーを使わなければならないという問題に直面しましたが、2つのコンポーネントを同じ画面に同時に表示する必要がありました。サービスにtimerObservableを作成しました。両方のコンポーネントでタイマーをサブスクライブしましたが、どうなったのですか?同期されません。新しいサブスクリプションは常に独自のストリームを作成するためです。

私が言いたいのは、1つのタイマーを複数の場所で使用する場合、常に.publishReplay(1).refCount() オブザーバーの最後に置くと、毎回同じストリームが公開されるためです。

例:

this.startDateTimer = Observable.combineLatest(this.timer, this.startDate$, (localTimer, startDate) => {
  return this.calculateTime(startDate);
}).publishReplay(1).refCount();

実装を共有できますか?
Nitish Kumar 2017

1

RxJSをサービスとして使用してこれを容易にするnpmパッケージを見つけました。

https://www.npmjs.com/package/ng2-simple-timer

同じコンポーネントで何度も使用している場合でも、既存のタイマーを「サブスクライブ」してバジリオンタイマーを作成する必要はありません。


1

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


0
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 => { },
    );
}
弊社のサイトを使用することにより、あなたは弊社のクッキーポリシーおよびプライバシーポリシーを読み、理解したものとみなされます。
Licensed under cc by-sa 3.0 with attribution required.