javascript - Angular 2 中的时间倒计时

标签 javascript angular

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

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/

相关文章:

JavaScript 在 30 秒后提交页面

添加构造函数时,Angular Component 不呈现 html

javascript - 有什么方法可以在 Angular 6 的嵌套 JSON 中动态显示单选按钮吗?

javascript - 来自 jquery 事件的回调函数

angular - 指定 rxjs observable 的 "error"处理程序的类型

javascript - 如何删除/清除传单中的标记?

angular - 如何从 Action ngxs 接收 http 响应

javascript - 更改 Angular 2 组件模板内的嵌套?

Javascript - 函数不返回数组,记录到控制台就好了

javascript - 无法获得 onClick 功能以在 body 上工作