📜  以角度显示数字时钟 - TypeScript 代码示例

📅  最后修改于: 2022-03-11 14:48:19.155000             🧑  作者: Mango

代码示例1
// in ts file

import { Component, OnInit } from '@angular/core';
import { Subscription, timer } from 'rxjs';
import { map, share } from "rxjs/operators";
import { OnDestroy } from '@angular/core';


@Component({
  selector: 'app-clock',
  templateUrl: './clock.component.html',
  styleUrls: ['./clock.component.scss']
})
export class ClockComponent implements OnInit, OnDestroy {

  date: Date = new Date();

  constructor() {
  }

  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();
    }
  }

}

// in html
 Simple Clock:
 
{{ time | date: 'hh:mm:ss a' }}
RxJS Clock:
{{ rxTime | date: 'hh:mm:ss a' }}