Programing

angular2에서 타이머를 만드는 방법

lottogame 2020. 8. 31. 08:19
반응형

angular2에서 타이머를 만드는 방법


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

이 플 런커 에서 작동 코드를 확인하십시오 .


또 다른 해결책은 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 : 탈퇴하는 것을 잊지 마세요.


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는 함수가 아닙니다"오류가 발생했습니다.

이 문제는 "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();    
}

I faced a problem that I had to use a timer, but I had to display them in 2 component same time, same screen. I created the timerObservable in a service. I subscribed to the timer in both component, and what happened? It won't be synched, cause new subscription always creates its own stream.

What I would like to say, is that if you plan to use one timer at several places, always put .publishReplay(1).refCount() at the end of the Observer, cause it will publish the same stream out of it every time.

Example:

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

You can simply use setInterval utility and use arrow function as callback so that this will point to the component instance.

For ex:

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

Inside your ngOnDestroy lifecycle hook, clear the interval.

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

Found a npm package that makes this easy with RxJS as a service.

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

You can 'subscribe' to an existing timer so you don't create a bazillion timers if you're using it many times in the same component.


If you look to run a method on ngOnInit you could do something like this:

import this 2 libraries from RXJS:

import {Observable} from 'rxjs/Rx';
import {Subscription} from "rxjs";

Then declare timer and private subscription, example:

timer= Observable.timer(1000,1000); // 1 second for 2 seconds (2000,1000) etc
private subscription: Subscription;

Last but not least run method when timer stops

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

That's all, 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 => { },
    );
}

참고URL : https://stackoverflow.com/questions/35813310/how-to-create-timer-in-angular2

반응형