我有一个带有 Phaser3 库的游戏。该游戏在文件phaser-game.component.ts
中。其中的类旨在与其他组件和服务进行交互。游戏的功能在此文件中,但在类中为否。我需要从scoreService
文件访问类中的特定方法或类的phaser-game.component.ts
属性。我该如何引用。
1)在类(preferable
)中从类外部并且在同一文件中的函数,或者
2)来自班级外部和同一文件内的班级分数(typeof "ScoreService"
)?
-将这些属性称为"this.updateHighscore"
-在类外部声明一个新的scoreService
以访问所需的功能
将代码移动到.html
文档中的脚本标签,而不是关联的.ts
文件
Phaser-game.component.ts:
import { ApiService } from './../api.service';
import { ScoreService } from './../score.service';
import { Component, OnInit, OnDestroy } from '@angular/core';
import { Physics } from 'phaser';
@Component({
selector: 'app-phaser-game',
templateUrl: './phaser-game.component.html',
styleUrls: ['./phaser-game.component.css']
})
export class PhaserGameComponent implements OnInit, OnDestroy {
user: any;
constructor(private api: ApiService, private score: ScoreService) {}
ngOnInit() {
game = new Phaser.Game(config);//Makes game
console.log("Component loaded");//Debug
this.api.getUser().subscribe(res => {//This works, gets user data
res == {} ? (
this.user = this.api.getUser().subscribe(res => {
this.user = res;
})
) : this.user = res;
});
}
ngOnDestroy(): void {
console.log("component being destroyed");
game.destroy();
moveSpeed = 200;
}
//This is the function that needs to be accessed
updateHighscore(): void {
this.score.updateHighscore(dataToSend);//This function works
}
}
//End of class
/*
Bunch of code relating to function of the game
*/
//This is the method that needs to do the update
//It's the games loop
update() {
if (gameOver) {
//Somehow get to the updateHighscore() method
return; //This ends the game loop
}
}
如果需要其他任何代码,请告诉我。据我所能进行的测试,一切都按预期进行,我只是无法进入此文件中的updateHighscore
类。谢谢!
预期结果:
PhaserGameComponent 类下的 updateHighscore 函数从其构造函数中声明的 scoreService 成功调用了 updateHighscore 函数。实际结果:
我尝试过的所有方法都无法访问 PhaserGameComponent 类下的 updateHighscore 函数。通常是"X is undefined"
,“ x”是我用来尝试使用该功能的所有内容。