创建计时器时出错
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了创建计时器时出错相关的知识,希望对你有一定的参考价值。
代码如下:
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());
错误的定义:类型'(e:any)=> any'的参数不能赋值给'()=> void类型的参数。那是什么?为什么我会收到此错误?
答案
看起来类型定义认为你的回调不应该带参数。试试这个:
this.timer0Id = this.st.subscribe('1sec', () => this.timer0callback());
以上是关于创建计时器时出错的主要内容,如果未能解决你的问题,请参考以下文章