html - Angular 8: Connecting two players together over a singleton service
问题描述
I'm trying to make a multiplayer game (Battleships). And the game is working, however i'm trying to make this a multiplayer game. And I've been trying to get two players connected to the same game. But this is not working for me. Any help would be greatly appreciated!
I have a service which I'm trying to make singleton over all modules and users/sessions
import { Injectable } from '@angular/core';
import {Player} from '../models/player';
@Injectable({
providedIn: 'root'
})
export class MultiplayerService {
constructor() { }
private static _ROOM1PLAYER: Player;
private static _ROOM1OPPONENT: Player;
whatsInPlayers() {
console.log(MultiplayerService.ROOM1PLAYER);
console.log(MultiplayerService.ROOM1OPPONENT);
}
static get ROOM1PLAYER(): Player {
return this._ROOM1PLAYER;
}
static set ROOM1PLAYER(value: Player) {
this._ROOM1PLAYER = value;
}
static get ROOM1OPPONENT(): Player {
return this._ROOM1OPPONENT;
}
static set ROOM1OPPONENT(value: Player) {
this._ROOM1OPPONENT = value;
}
}
- When i try to add a user to ROOM1PLAYER it works fine.
- When I try to add a user to ROOM1OPPONENT (ON A DIFFERENT PC/SESSION) it still works.
BUT, when i try to call the method whatsInPlayers() to see if both players are populated. I only get to see the one I've added on this session/PC and the other is "undefined".
Can someone guide me in the right direction to be able to get these static variables across all connections/sessions/pcs?
Thanks!
解决方案
尝试static
从 _ROOM1PLAYER 和 _ROOM1OPPONENT 属性中删除,并将内部whatsInPlayers
函数替换MultiplayerService
为this
.
此属性与实例相关,与静态属性不同。