在 Angular 中添加 date/time 服务 2

Adding a date/time service in Angular 2

我正在尝试在 Angular 2 中设置一个非常基本的服务。目标是在用户单击按钮时显示当前日期和时间。当我使用下面的代码时,出现以下错误:

Error during evaluation of "click" ORIGINAL EXCEPTION: TypeError: l_context.whatTime is not a function

时间组件:

@Component({
    template: `
      <h1>Time Test</h1>
      <button (click) = "whatTime()">Time</button>
      <h2>{{now}}</h2>
         `
})

    export class TimeComponent {
      now = Date();
      constructor(public timeService: TimeService) {
        this.now = timeService.whatTime();
    }
}

服务:

@Injectable()
    export class TimeService {

      whatTime() {
      return new Date();
    }
}

对我做错了什么有什么想法吗?

改用这个

Plunker

<button (click) = "now = timeService.whatTime()">Time</button>

但它可能会产生开发模式错误。

更好的方法是在服务中添加一个 Observable,以预定义的时间间隔通知时间变化

@Injectable()
export class TimeService {

  constructor() {
    this.whatTime = Observable.interval(1000).map(x => new Date()).share();
  }
}
<!-- <button (click) = "whatTime()">Time</button> -->
  <h2>{{timeService?.whatTime | async}}</h2>

I have found that @günter-zöchbauer's observable-based solution takes a little while to load up (atleast in plnkr) ... haven't done official performance tests but ....

这里有一个不使用 rxjs 制作实时时钟的简单方法。

(见Plunker of this working over here

您可以像这样在模板中使用它:

<p>{{ now }}</p>

<!-- OR something like  -->

<h2>{{ now |  date:'yMMMdjms'  }}</h2>

这里是组件 class 定义:

class ClockComponent {
  interval;

  now = new Date();

  constructor(){
    this.interval = setInterval(()=> { 
      this.now = new Date() ;

    })
  }

  ngOnDestroy(){
    clearInterval(this.interval)
  }

}

就是这样!