首页 > 解决方案 > Angular 6 的时差

问题描述

我需要在每秒更新的 UI 上显示时差。

我尝试的是:

组件.ts

import { Component, OnInit } from '@angular/core';
import 'rxjs/add/observable/of';
import 'rxjs/add/observable/interval';
import 'rxjs/add/operator/map';
import { Observable, Subscription } from 'rxjs/Rx';
import { DateUtil } from '../../../framework/Utils/DateUtil';

@Component({
  selector: 'app-time-difference',
  templateUrl: './time-difference.component.html',
  styleUrls: ['./time-difference.component.scss']
})
export class TimeDifferenceComponent implements OnInit {
  orderTime = '14-09-2018 14:00:00';
  today = new Date();

  clock: Observable<any>;
  timeDifference: string;

  constructor() { }

  ngOnInit() {
    this.clock = Observable
      .interval(1000)
      .map(() => {
        const orderDate = DateUtil.getDatefromString(this.orderTime, 'DD-MM-YYYY HH:mm:ss');
        const timeDifference = DateUtil.getDateDiffInHours(orderDate, new Date());
        return timeDifference;
      });

    this.clock.subscribe(
      res => console.log(res)
      );
  }
}

.html

<div class="row mt-5 ml-5" style="margin-left:20px;">
    {{clock | async}}
</div>

DateUtil 函数

static getDateDiffInHours(startDate, endDate)
{
    let start = moment(startDate);
    let end = moment(endDate);
    let diff = moment.duration(end.diff(start));
    let milliSec = diff.milliseconds();
    let dateString = moment(milliSec).format('DD-MM-YYYY HH:mm:ss');
    return moment(dateString, 'DD-MM-YYYY HH:mm:ss').toDate();
}

有人可以告诉我我在哪里犯了错误吗?

因为我没有在 UI 中获得更新时差,但我在控制台中获得了更新持续时间对象

UI 上的静态结果

PT10H13M26.992S

标签: angularrxjsobservablemomentjsangular6

解决方案


好吧,这并不是说视图没有更新。如果您仔细查看控制台中的输出 - 它始终是相同的日期。获取时差的实现相当混乱,可以用更好的方式完成。

如果没有任何外部 util 函数,实现可能如下所示:

import { Component, OnInit } from '@angular/core';
import {Observable} from 'rxjs/Rx';
import {DateUtil} from '../utils/DateUtil';
import * as moment from 'moment';

@Component({
  selector: 'app-time-difference',
  templateUrl: './time-difference.component.html',
  styleUrls: ['./time-difference.component.css']
})
export class TimeDifferenceComponent implements OnInit {
  orderTime = '14-09-2018 14:00:00';
  clock: Observable<any>;

  constructor() { }

  ngOnInit() {
    // order date in millis (can be computed once)
    const orderDate: number = moment(this.orderTime, 'DD-MM-YYYY HH:mm:ss').valueOf();
    this.clock = Observable
      .interval(1000)
      .map(() => {
        return Date.now() - orderDate;
      });

    this.clock.subscribe(
      res => console.log(res) // Output difference in millis
    );
  }
}

在模板中,您可以通过以下方式使用 Angular Date 管道:

<div class="row mt-5 ml-5" style="margin-left:20px;">
    {{(clock | async) | date:'dd HH:mm:ss'}}
</div>

如果您想在输出中使用一些特殊的日期格式,您可以以您喜欢的任何方式映射可观察的时钟。例如:

const orderDate: number = moment(this.orderTime, 'DD-MM-YYYY HH:mm:ss').valueOf();
    this.clock$ = Observable
      .interval(1000)
      .map(() => {
        return Date.now() - orderDate;
      })
      .map((millis: number) => {
        return moment.duration(millis);
      })
      .publishReplay(1).refCount(); // so that calculation is performed once no matter how many subscribers

this.days$ = this.clock$.map(date => date.days());
this.hours$ = this.clock$.map(date => date.hours());
this.minutes$ = this.clock$.map(date => date.minutes());
this.seconds$ = this.clock$.map(date => date.seconds());

在模板中:

<ul>
    <li><span id="days">{{days$ | async}}</span>Days</li>
    <li><span id="hours">{{hours$ | async}}</span>Hours</li>
    <li><span id="minutes">{{minutes$ | async}}</span>Minutes</li>
    <li><span id="seconds">{{seconds$ | async}}</span>Seconds</li>
</ul>

希望这可以帮助。


推荐阅读