我是Angle和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);
}
我到底在做什么错?另外,我不仅需要工作代码。我需要了解为什么这是一个问题。我尝试通过类似的查询来阅读其他一些问题,但是我对那里的问题并不清楚。
答案 0 :(得分:0)
正如@harmandeepsinghkalsi在评论中指出的那样,问题在于setInterval的调用方式,而不是特定于Angular / TS的问题。我可以通过对我的代码进行较小的调整来克服此问题。回答这个问题只是为了解决问题,并为以后的堆叠者提供最新的答案。
这是新的修改代码:
@Output() counterEmitter = new EventEmitter<number>();
counter = 0;
intervalId: any;
initiateGame() {
this.intervalId = setInterval(() => {
this.counter++;
this.counterEmitter.emit(this.counter);
console.log(this.counter);
}, 1000);
}
stopGame() {
clearInterval(this.intervalId);
}
ngOnInit(): void {
}