如何使用 Rxjs Observable 和 Async Pipe 在 Angular 4 中为每日重复事件创建倒数计时器
Posted
技术标签:
【中文标题】如何使用 Rxjs Observable 和 Async Pipe 在 Angular 4 中为每日重复事件创建倒数计时器【英文标题】:How to create a countdown timer for a daily recurring event in Angular 4 using Rxjs Observable and Async Pipe 【发布时间】:2018-05-10 02:41:14 【问题描述】:我正在尝试使用 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,以便我可以在我的模板中将它与异步管道一起使用?
【问题讨论】:
【参考方案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>
【讨论】:
以上是关于如何使用 Rxjs Observable 和 Async Pipe 在 Angular 4 中为每日重复事件创建倒数计时器的主要内容,如果未能解决你的问题,请参考以下文章
如何在 Angular/RxJS 中合并两个 observable?
如何在 Angular 4 中推送到数组的 Observable? RxJS