gpt4 book ai didi

javascript - Angular 2 中的时间倒计时

转载 作者:太空狗 更新时间:2023-10-29 16:55:56 26 4
gpt4 key购买 nike

我想要这样的日期倒计时:

http://codepen.io/garethdweaver/pen/eNpWBb

但在 Angular 2 中,我发现这个 plunkr 每 500 毫秒将数字加 1:

https://plnkr.co/edit/pVMEbbGSzMwSBS4XEXJI?p=preview

这是代码:

import {Component,Input} from 'angular2/core';
import {Observable} from 'rxjs/Rx';

@Component({
selector: 'my-app',
template: `
<div>
{{message}}
</div>
`
})
export class AppComponent {

constructor() {
Observable.interval(1000)
.map((x) => x+1)
.subscribe((x) => {
this.message = x;
}):
}
}

但我希望有一个日期需要一秒直到达到 0。

最佳答案

import { Component, NgOnInit, ElementRef, OnInit, OnDestroy } from 'angular2/core';
import { Observable, Subscription } from 'rxjs/Rx';

@Component({
selector: 'my-app',
template: `
<div>
{{message}}
</div>
`
})
export class AppComponent implements OnInit, OnDestroy {

private future: Date;
private futureString: string;
private counter$: Observable<number>;
private subscription: Subscription;
private message: string;

constructor(elm: ElementRef) {
this.futureString = elm.nativeElement.getAttribute('inputDate');
}

dhms(t) {
var days, hours, minutes, seconds;
days = Math.floor(t / 86400);
t -= days * 86400;
hours = Math.floor(t / 3600) % 24;
t -= hours * 3600;
minutes = Math.floor(t / 60) % 60;
t -= minutes * 60;
seconds = t % 60;

return [
days + 'd',
hours + 'h',
minutes + 'm',
seconds + 's'
].join(' ');
}


ngOnInit() {
this.future = new Date(this.futureString);
this.counter$ = Observable.interval(1000).map((x) => {
return Math.floor((this.future.getTime() - new Date().getTime()) / 1000);
});

this.subscription = this.counter$.subscribe((x) => this.message = this.dhms(x));
}

ngOnDestroy(): void {
this.subscription.unsubscribe();
}
}

HTML:

 <my-app inputDate="January 1, 2018 12:00:00">Loading...</my-app>

关于javascript - Angular 2 中的时间倒计时,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36461089/

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