我正在尝试创建一个动态显示当前时间的时钟组件。
Problem: Time is shown as expected on load (HH:mm A), but the clock does not change at all.
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
保存的是初始化值,而不是更新后的值,因此,以下是与您的组件
相同,但版本较小。
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");
})
);
}
}
以及您的 View 本来的样子。
这是一个 stackblitz 示例,请自行检查 https://stackblitz.com/edit/angular-moment-rxjs
关于javascript - 使用momentjs显示当前时间,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53670691/