创建计时器时出错

时间:2017-12-26 13:15:23

标签: angular typescript timer

代码如下:

import {Component, OnInit} from '@angular/core';
import {SimpleTimer} from 'ng2-simple-timer';

@Component({
'selector': 'my-app',
'template': `
    <p>
    ng2-simple-timer is available in
      <a href="https://www.npmjs.com/package/ng2-simple-timer">npm</a> and 
  <a href="https://github.com/J-Siu/ng2-simple-timer">github</a>.
This example is available in
  <a href="https://github.com/J-Siu/ng2-simple-timer-example">github</a>.
</p>
    <div style="border: 1px solid;margin:5px;padding:5px">
    <h3>{{title}}</h3>
    <div>{{counter0}}</div>


</div>`
})
export class AppComponent implements OnInit {
title = 'Angular2 Simple Timer Service Example';

counter0 = 0;
timer0Id: string;
timer0button = 'Subscribe';


// Define SimpleTimer as 'st'
constructor(private st: SimpleTimer) { }

ngOnInit() {
    this.st.newTimer('1sec',1);
    this.subscribeTimer0();

}



subscribeTimer0() {
    if (this.timer0Id) {
        // Unsubscribe if timer Id is defined
        this.st.unsubscribe(this.timer0Id);
        this.timer0Id = undefined;
        this.timer0button = 'Subscribe';
        console.log('timer 0 Unsubscribed.');
    } else {
        // Subscribe if timer Id is undefined
        this.timer0Id = this.st.subscribe('1sec', e => this.timer0callback());
        this.timer0button = 'Unsubscribe';
        console.log('timer 0 Subscribed.');
    }
    console.log(this.st.getSubscription());
}



timer0callback() {
    this.counter0++;
}


}

我正在努力学习计时器。我在互联网上找到了这个代码。我安装了ng2-simple-timer。但是我收到了一个错误。 错误发生在

 this.timer0Id = this.st.subscribe('1sec', e => this.timer0callback());

错误的定义:类型的参数&#39;(e:any)=&gt;任何&#39;不能分配给&#39;()=&gt; void类型的参数。 那是什么?为什么我会收到此错误?

1 个答案:

答案 0 :(得分:0)

看起来类型定义认为你的回调不应该带参数。试试这个:

this.timer0Id = this.st.subscribe('1sec', () => this.timer0callback());