繁体   English   中英

使用moment.js显示当前时间

[英]Display current time with momentjs

我正在尝试创建一个时钟组件,以动态显示当前时间。

问题:时间显示为预期的负载( HH:mm A ),但时钟完全不变。

clock.component.ts:

import {
    ChangeDetectionStrategy,
    Component,
    OnInit
} from "@angular/core";
import { Observable, interval } from "rxjs";
import { map, distinctUntilChanged } from "rxjs/operators";
import * as moment from "moment";

@Component({
    selector: "app-clock",
    templateUrl: "./clock.component.html",
    changeDetection: ChangeDetectionStrategy.OnPush
})
export class ClockComponent implements OnInit {

    pageLoaded: moment.Moment;
    time: Observable<string>;

    constructor() {}

    ngOnInit() {
        this.pageLoaded = moment(new Date());

        this.time = interval(1000).pipe(
            map(() => this.pageLoaded.format("HH:mm A")),
            distinctUntilChanged()
        );
    }
}

clock.component.html:

<div>{{ time | async }}</div>

首先,如果您在哪里,我将使用@types/moment使我的生活更轻松(可选)。

那么,为什么“时钟根本不改变”?

因为一旦页面加载,您就初始化了时钟的值,并且此值基本上不会更新,因此this.time保留了初始化的值,而不是更新的值,因此,以下内容与您的component相同,但带有少许版本。

import {
    ChangeDetectionStrategy,
    Component,
    OnInit
} from "@angular/core";
import { Observable, interval } from "rxjs";
import { map, distinctUntilChanged } from "rxjs/operators";
import moment, { Moment } from "moment"; // using @types/moment

@Component({
    selector: "app-clock",
    templateUrl: "./clock.component.html",
    changeDetection: ChangeDetectionStrategy.OnPush
})
export class ClockComponent implements OnInit {

    pageLoaded: Moment;
    time: Observable<string>;

    constructor() {}

    ngOnInit() {
    this.time = interval(1000*60).pipe( // why you need 1s interval with HH:mm time format simply update it every minute not every second.
      map(() => {
        this.pageLoaded = moment(new Date()); // you need the value of now not the value of the initialized time.
        return this.pageLoaded.format("HH:mm A");
      })
    );
  }
}

和您的看法一样。

这是一个stackblitz示例自己检查一下https://stackblitz.com/edit/angular-moment-rxjs

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM