gpt4 book ai didi

javascript - 如何使用 Rxjs Observable 和 Async Pipe 在 Angular 4 中为每日重复发生的事件创建倒数计时器

转载 作者:行者123 更新时间:2023-11-30 20:57:30 25 4
gpt4 key购买 nike

我正在尝试使用 Rxjs Observable 和 Async Pipe 为 Angular 4 中的每日重复事件创建一个倒数计时器。这是我的组件:

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

}

}

这是我的模板:

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

所以,我的问题是,我如何利用 RXJS 计时器和其他运算符返回一个 Observable,以便我可以在我的模板中将它与异步管道一起使用?

最佳答案

做一个基于秒的简单版本,

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>

关于javascript - 如何使用 Rxjs Observable 和 Async Pipe 在 Angular 4 中为每日重复发生的事件创建倒数计时器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47501111/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com