以角度显示时间/时钟

San*_*osh 3 rxjs angular

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

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);
  }
Run Code Online (Sandbox Code Playgroud)

这段代码可以正常工作,但是一段时间后应用程序崩溃了。有没有其他方法可以在angular4 / 5/6中显示时间?

Nir*_*iya 6

内部component.ts

time = new Date();

ngOnInit() {
    setInterval(() => {
       this.time = new Date();
    }, 1000);
}
Run Code Online (Sandbox Code Playgroud)

内部component.html

{{ time | date: 'hh:mm:ss a' }}
Run Code Online (Sandbox Code Playgroud)

工作演示

  • 我也建议存储并清除内部,如下所示:`ngOnInit(){this.intervalID = setInterval(()=> {this.time = new Date();},1000); } ngOnDestroy(){clearInterval(this.intervalID); }` (4认同)
  • 解释为什么这样做是有用的,以及为什么OP的原始代码不起作用。否则他们什么都不学。 (2认同)
  • 不过,评论是“临时的”,大多数人只会阅读最热门/接受的答案。 (2认同)

Pur*_*ani 5

或者,您可以使用可观察量:

private _time$: Observable<Date> = timer(0, 1000).pipe(
  map(tick => new Date()),
  shareReplay(1)
);

get time() {
  return this._time$;
}
Run Code Online (Sandbox Code Playgroud)

在你的html中:

{{ time | async | date: 'hh:mm:ss a' }}
Run Code Online (Sandbox Code Playgroud)

好处:当你在HTML中使用async管道时,你不再需要考虑订阅和取消订阅以及担心内存泄漏。它完全安全且易于使用!