首页 > 解决方案 > 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;
  }
}

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!

标签: htmlangulartypescriptmultiplayer

解决方案


尝试static从 _ROOM1PLAYER 和 _ROOM1OPPONENT 属性中删除,并将内部whatsInPlayers函数替换MultiplayerServicethis.

此属性与实例相关,与静态属性不同。


推荐阅读