单例类可以在打字稿中继承吗?

时间:2019-02-15 07:02:47

标签: typescript singleton

我需要继承单例类并重写它的方法。打字稿有可能吗?或以其他方式在打字稿中实施这种类型的方案。

//家长班

export class SFSCommands {
    static instance: SFSCommands;
    protected constructor() {
        if (SFSCommands.instance) {
            return SFSCommands.instance;
        }

        setInterval(() => {
            this.initSfsCommands('sss');
        }, 2000);
    }

    static getInstance() {
        if (!SFSCommands.instance) {
            SFSCommands.instance = new SFSCommands();
        }
        return SFSCommands.instance;
    }

    initSfsCommands(e: any) {
        console.log('comming in service');
    }
}

// ****儿童班***********

import { SFSCommands } from '../utility/sfscommands';

export abstract class GameModel extends SFSCommands {
    roomName: string;

    constructor() {
        super();
        console.log(this);
    }

    // called from child whien game component inisilized

    initSfsCommands(event: any) {
        console.log('game model');
    }

}

我从我的 app.component.ts 文件

中调用 SFSCommands.getInstance()

2 个答案:

答案 0 :(得分:1)

Angular注入/服务类是单例。

function addRecipe(e) {

    e.preventDefault();

    var recipe = {
      param1: 'value1',
      param2: 'value2'
    };

    console.log('step 2')

    let xml = new XMLHttpRequest();
    xml.open("POST", "/add-recipe", true);
    //Specify the type of data to be sent
    xml.setRequestHeader("Content-type", "application/json; charset=utf-8");
    xml.send(JSON.stringify(recipe));
    console.log('step 3');

    //Get the form and submit it
    form.submit();
}

当您第一次将其注入组件时,它将被实例化。

@Injectable({providedIn: 'root'})
export class GlobalService {}

答案 1 :(得分:0)

这不好,但是有可能

export class GameModel extends SFSCommands {
  static getInstance() {
    super.getInstance().initSfsCommands = (event: any) => {
      console.log('game model');
    }
    return GameModel.instance;
  }
}

,您应该致电GameModel.getInstance()而不是SFSCommands.getInstance()

希望获得帮助