code

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

starcafe 2023. 10. 30. 21:10
반응형

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

저는 Angular 2의 타이머가 필요한데, 이 타이머는 시간 간격 후에 체크하고 몇 가지 작업을 수행합니다(일부 함수를 호출할 수도 있습니다).

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

추신: 구독을 취소하는 것을 잊지 마세요.

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

error를 했습니다. 교체로 해결되었습니다.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();    
}

간단히 setInterval 유틸리티를 사용하고 화살표 기능을 콜백으로 사용하여 다음을 수행할 수 있습니다.this는 구성 요소 인스턴스를 가리킵니다.

다음의 경우:

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

ngOnDestroy 라이프사이클 후크 안에서 간격을 지웁니다.

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

타이머를 사용해야 하는 문제가 있었는데, 같은 화면으로 2개의 컴포넌트에 동시에 표시해야 했습니다.서비스에서 관찰 가능한 타이머를 만들었습니다.두 부품 모두 타이머를 가입했는데, 어떻게 된 건가요?새 구독은 항상 자체 스트림을 생성하기 때문에 동기화되지 않습니다.

제가 말하고 싶은 것은, 만약 당신이 여러 장소에서 하나의 타이머를 사용할 계획이라면, 항상 다음과 같이 하십시오..publishReplay(1).refCount()옵저버가 끝날 때마다 같은 스트림을 퍼낼 것이기 때문입니다.

예:

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

RxJS as a Service로 이것을 쉽게 해주는 ppm 패키지를 찾았습니다.

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

동일한 구성 요소에서 여러 번 사용하는 경우 기존 타이머에 '구독'할 수 있으므로 엄청난 수의 타이머를 만들지 않습니다.

ngOnInit에서 메서드를 실행하려고 하면 다음과 같은 작업을 수행할 수 있습니다.

RXJS에서 다음 두 라이브러리 가져오기:

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

이게 다예요, 앵글 5.

일정시간 경과 후 타이머 설정 및 자동 호출 서비스

 // Initialize from ngInit
    ngOnInit(): void {this.getNotifications();}
    
    getNotifications() {
        setInterval(() => {this.getNewNotifications();
        }, 60000);  // 60000 milliseconds interval 
    }
    getNewNotifications() {
        this.notifyService.getNewNotifications().subscribe(
            data => { // call back },
            error => { },
        );
    }

Angular의 최신 버전에서 Observable.timer는 지원되지 않습니다.@Abdulrahman Alghayer 예제에서 비트 변경과 함께 사용할 수 있습니다.

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

@Component({
    selector: 'my-app',
    template: 'Ticks (every second) : {{ticks}}'
})
export class AppComponent {
  ticks =0;
  ngOnInit(){
    let timer$ = timer(2000,1000);
    timer$.subscribe(t=>this.ticks = t);
  }
}

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

반응형