【问题标题】:Display time/clock in angular以角度显示时间/时钟
【发布时间】:2019-06-14 18:58:26
【问题描述】:

我正在使用以下方法在我的应用中显示时间?

constructor(private datePipe: DatePipe) {}
ngOnInit() {
    this.getTime();
    this.date = this.datePipe.transform(new Date(), "dd/MM/yyyy");
  }
 getTime() {
    setInterval(() => {
      this.time = this.datePipe.transform(new Date(), "HH:mm:ss");
      this.getTime();
    }, 1000);
  }

这段代码运行良好,但一段时间后应用程序崩溃了。 有没有其他方法可以在 angular4/5/6 中显示时间?

【问题讨论】:

  • setInterval 每次调用时都会产生一个额外的并行间隔,为什么getTime 会递归调用自身?另外你为什么不把管道放在模板中,然后就做this.time = new Date();
  • 将尝试更新
  • [性能] 这是在屏幕上显示时钟的错误方式。每个时间间隔完成 1000 毫秒 Angular 事件侦听器被触发。从 @angular/core 尝试 ngZone 并在其中运行 runOutsideAngular 方法

标签: angular rxjs


【解决方案1】:

component.ts 内部

  time = new Date();
  rxTime = new Date();
  intervalId;
  subscription: Subscription;

  ngOnInit() {
    // Using Basic Interval
    this.intervalId = setInterval(() => {
      this.time = new Date();
    }, 1000);

    // Using RxJS Timer
    this.subscription = timer(0, 1000)
      .pipe(
        map(() => new Date()),
        share()
      )
      .subscribe(time => {
        this.rxTime = time;
      });
  }

  ngOnDestroy() {
    clearInterval(this.intervalId);
    if (this.subscription) {
      this.subscription.unsubscribe();
    }
  }

component.html 内部

Simple Clock:
<div>{{ time | date: 'hh:mm:ss a' }}</div>
RxJS Clock:
<div>{{ rxTime | date: 'hh:mm:ss a' }}</div>

工作demo

【讨论】:

  • @Santhosh 请检查添加到答案中的工作演示链接。
  • 我还建议存储和清除 inveral,如下所示:ngOnInit() { this.intervalID = setInterval(() =&gt; { this.time = new Date(); }, 1000); } ngOnDestroy() { clearInterval(this.intervalID); }
  • 解释一下为什么会起作用,以及为什么 OP 的原始代码不起作用。否则他们什么也学不到。
  • @jonrsharpe 感谢您的建议,我想您已经在之前的评论中解释了为什么它不起作用。
  • 评论是临时的,不过,大多数人只会阅读最热门/接受的答案。
【解决方案2】:

使用可观察和“onPush”变化检测的替代方法

import { ChangeDetectionStrategy, Component } from '@angular/core';
import { Observable, timer } from 'rxjs';
import { map } from 'rxjs/operators';

@Component({
    selector: 'time',
    template: "{{ $time | async | date: 'hh:mm:ss a' }}",
    styleUrls: ['./time.component.scss'],
    changeDetection: ChangeDetectionStrategy.OnPush,
})
export class TimeComponent {
    public $time: Observable<Date> = timer(0, 1000).pipe(map(() => new Date()));
}

【讨论】:

    【解决方案3】:

    或者,您可以使用 observables:

    private _time$: Observable<Date> = timer(0, 1000).pipe(
      map(tick => new Date()),
      shareReplay(1)
    );
    
    get time() {
      return this._time$;
    }
    

    在你的 html 中:

    {{ time | async | date: 'hh:mm:ss a' }}
    

    【讨论】:

      猜你喜欢
      • 2012-06-16
      • 2021-05-24
      • 1970-01-01
      • 2014-10-05
      • 2020-07-22
      • 2014-07-03
      • 1970-01-01
      • 2012-08-21
      • 2017-03-25
      相关资源
      最近更新 更多