【发布时间】:2020-06-28 09:50:27
【问题描述】:
我是 Angular 和 TS 的新手。试图创建一个组件来使用setInterval 方法。这是我的 TS 组件
import { Component, OnInit, EventEmitter } from '@angular/core';
@Component({
selector: 'app-gamecontrol',
templateUrl: './gamecontrol.component.html',
styleUrls: ['./gamecontrol.component.css']
})
export class GamecontrolComponent implements OnInit {
constructor() { }
counterEmitter = new EventEmitter<number>();
counter = 0;
initiateGame = setInterval(() => {
this.counter++;
this.counterEmitter.emit(this.counter);
console.log(this.counter);
}, 1000);
stopGame = clearInterval(this.initiateGame);
ngOnInit(): void {
}
}
这是调用它的 HTML 组件:
<h3>Welcome to the game of Chances</h3>
<div class="container">
<div class="row">
<button class="btn btn-primary" (click)="initiateGame()">Start Game</button>
</div>
<div class="row">
<button class="btn btn-primary" (click)="stopGame()">Stop Game</button>
</div>
</div>
当我尝试运行应用程序时,出现以下错误:
RROR in src/app/gamecontrol/gamecontrol.component.html:4:50 - error TS2349: This expression is not callable.
Type 'Number' has no call signatures.
4 <button class="btn btn-primary" (click)="initiateGame()">Start Game</button>
~~~~~~~~~~~~
src/app/gamecontrol/gamecontrol.component.ts:5:16
5 templateUrl: './gamecontrol.component.html',
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Error occurs in the template of component GamecontrolComponent.
src/app/gamecontrol/gamecontrol.component.html:7:50 - error TS2349: This expression is not callable.
Type 'void' has no call signatures.
7 <button class="btn btn-primary" (click)="stopGame()">Stop Game</button>
~~~~~~~~
src/app/gamecontrol/gamecontrol.component.ts:5:16
5 templateUrl: './gamecontrol.component.html',
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Error occurs in the template of component GamecontrolComponent.
此外,当我如下所示声明我的函数时,它不会出现任何错误并且工作正常。这两种方法有什么区别?
initiateGame() {
setInterval(() => {
this.counter++;
this.counterEmitter.emit(this.counter);
console.log(this.counter);
}, 1000);
}
我到底做错了什么?此外,我不仅需要工作代码。我需要了解为什么这是一个问题。我尝试用类似的查询阅读其他几个问题,但我并没有清楚地理解那里的问题。
【问题讨论】:
-
在第一种方法中,initialGame 不是一个函数。它是一个变量,具有从 setInterval 返回的唯一整数。第二种方法是一个函数。请参阅此内容以了解 setInterval 返回 bitdegree.org/learn/… 的内容。
-
@HarmandeepSinghKalsi 知道了,我相信问题在于我对 setInterval 的了解,而不是 TS。谢谢!
标签: javascript angular typescript function