2017-11-26 10 views
1

Rxjs Observable 및 Async Pipe를 사용하여 Angular 4로 매일 되풀이되는 이벤트에 대한 카운트 다운 타이머를 만들려고합니다.Rxjs Observable 및 Async Pipe를 사용하여 Angular 4로 매일 되풀이되는 이벤트를위한 카운트 다운 타이머를 만드는 방법

<span class="auctions-text">Auctions close in <b>{{ hoursLeft }} hours {{ minutesLeft }}m {{ secondsLeft }}s</b></span> 

그래서, 내 질문은, 내가 RXJS 타이머 및 기타 사업자는 관찰 가능한을 반환 활용 얼마나, 내가 사용할 수 있도록 : 여기

interface Time { 
    hours: number; 
    minutes: number; 
    seconds: number; 
} 
@Component({ 
    selector: 'app-header-area', 
    templateUrl: './header-area.component.html', 
    styleUrls: [ './header-area.component.scss' ] 
}) 
export class HeaderAreaComponent { 
    @Input() language: LanguageState; 
    @Input() menu: MenuState; 

    remaining: Time; 
    hoursLeft: number; 
    minutesLeft: number; 
    secondsLeft: number; 

    timeLeft(date) { 
    // UTC times 
    const utc_hours = date.getUTCHours(); 
    const utc_minutes = date.getUTCMinutes(); 
    const utc_seconds = date.getUTCSeconds(); 
    // End hour 
    const end_hour = 20; 
    // Difference in hours, minutes, seconds 
    const difference_hours = (utc_hours <= end_hour) ? (end_hour - utc_hours) : (24 + end_hour) - utc_hours; 
    const difference_minutes = 60 - (utc_minutes % 60) - 1;; 
    const difference_seconds = 60 - (utc_seconds % 60) - 1;; 
    return <Time>{ 
     hours: difference_hours, 
     minutes: difference_minutes, 
     seconds: difference_seconds, 
    } 
    } 

    constructor() { 
    timer(0, 1000).subscribe(() => { 
     const time = this.timeLeft(new Date()); 
     const { hours, minutes, seconds } = time; 
     this.hoursLeft = hours; 
     this.minutesLeft = minutes; 
     this.secondsLeft = seconds; 
    }); 

    } 

} 

내 templte입니다 : 여기 내 구성 요소입니다 내 서식 파일에 비동기 파이프가 있습니까? 초를 기반으로 간단한 버전을하는

답변

1

,

const endHours = 20 
const endSeconds = endHours * 60 * 60; 
const countdown$ = Observable.timer(0, 1000) 
    .map(x => endSeconds - x) 
    .takeWhile(x => x > 0); 

const hoursLeft$ = countdown$.map(x => calcHoursFromSecondsRemaining(x)); 
const minsLeft$ = countdown$.map(x => calcMinsFromSecondsRemaining(x)); 
const secsLeft$ = countdown$.map(x => calcSecondsFromSecondsRemaining(x)); 

<span>{{ hoursLeft$ | async }}</span> 
<span>{{ minsLeft$ | async }}</span> 
<span>{{ secsLeft$ | async }}</span>