0

我正在尝试在 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();
    }
}

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

4

2 回答 2

5

改用这个

普朗克

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

但它可能会产生 devmode 错误。

更好的方法是向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>
于 2016-03-12T20:57:41.747 回答
0

我发现@günter-zöchbauer的基于 observable 的解决方案需要一些时间来加载(至少在 plnkr 中)......尚未进行官方性能测试,但是......

这是一种不使用 rxjs 制作实时时钟的简单方法。

(请参阅此处工作的 Plunker

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

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

<!-- OR something like  -->

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

这是组件类定义:

class ClockComponent {
  interval;

  now = new Date();

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

    })
  }

  ngOnDestroy(){
    clearInterval(this.interval)
  }

}

而已!

于 2017-04-16T11:08:10.593 回答