Is it possible to inherit a singleton class in TypeScript?

Is it possible to inherit a singleton class and override its method in TypeScript? Or is there any other way to implement this type of scenario in TypeScript?

// Parent Class

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');
    }
}

//**** Child Class ***********

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

export abstract class GameModel extends SFSCommands {
    roomName: string;

    constructor() {
        super();
        console.log(this);
    }
    
    // called from child when game component initialized
    
    initSfsCommands(event: any) {
        console.log('game model');
    }
}

I call SFSCommands.getInstance() from my app.component.ts file

Answer №1

In the world of Angular, an injectable/service class operates as a singleton.

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

Once injected into a component for the first time, it will be created and instantiated.

constructor(private globalService: GlobalService){}

Answer №2

While it may not be the most pleasant option, it is indeed achievable.

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

Ensure to utilize GameModel.retrieveInstance() rather than SFSCommands.getInstance()

Trust this guidance proves beneficial.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Tips for updating the display after making an angular $http request using rxjs Observables

I have a project where I am utilizing angular's $http service to fetch data from a remote endpoint. I am keen on incorporating rxjs Observables, hence the call in my service is structured as follows: userInfo() : Rx.Observable<IUserInfo> { ...

Using Angular 2 to assign a pipe dynamically from a variable

Could something like the following be achievable: {{property | some_variable_name}} I am aiming to utilize a pipe that is defined in a JSON configuration (or variable), but I am uncertain if it is feasible to include the pipe name within the interpolatio ...

Steps for validating the correct number of parameters passed to a function

Currently, I am developing a program with TypeScript and TSLint serving as the linter. Below is my preferred list of rules found in tslint.json: { "extends": "tslint:recommended", "rules": { "comment-format": [false, "check-space"], ...

Execute the function when the observable is subscribed to

I'm currently working on creating a custom component that can interact with an observable passed in through an input. The goal is to show/hide elements based on the state of the observable. Here's what I have in mind: @Input() observable: Observ ...

Fulfill several promises and execute an HTTP request in Angular 2

At this moment, I am in need of retrieving two elements from my storage, each providing me with a promise. The challenge lies in using these promises to create an HTTP request in Angular 2. Despite numerous attempts, I have been unsuccessful in finding the ...

The final value of a loop is consistently returned each time

Creating a loop to generate objects. Action.ts public campaing:any = { 'id': '', 'campaing_code': '', 'campaing_type': '', 'start_date': this.currentDate, 'end ...

Creating an Array in TypeScript

Is it possible to declare a global array in Typescript so that it can be accessed using "this" from any part of the code? In javascript, I would typically declare it as "var anArray=[]". What is the equivalent way of doing this in Typescript? Using anArra ...

What is the best approach for implementing the DRY principle in NestJS when developing controllers?

Greetings! I've developed a fundamental controller named BaseController, which includes basic endpoints... import { Get, Post, Put, Delete, HttpStatus, Request, Response } from '@nestjs/common'; import { MessageCodeError } from './../ ...

The object MediaStreamRecorder is not able to be used as a constructor

Just starting my Angular6 journey and I'm experimenting with the MediaStreamRecorder feature. Somehow, I must be messing up the definition of MediaStreamRecorder because all I get is this frustrating error message: TypeError: msr__WEBPACK_IMPORTED_MOD ...

The optimal time to register for events within the Vue lifecycle

Currently, I am developing a Vue2 component using vue-component that includes a subcomponent. Here is an example: <note :bus="bus" :itemId="selectedId"></note> The subcomponent contains the following code snippet: <textarea v-model="text" ...

Error in Transpilation of iOS Delegate in NativeScript (Variable __metadata Not Found)

I'm facing an issue while trying to incorporate an iOS delegate in a NativeScript plugin. The error I'm encountering reads as follows: Terminating app due to uncaught exception 'NativeScript encountered a fatal error: ReferenceError: Can& ...

Why is there empty white space showing in the select option drop down, even though the data is being bound correctly

When creating a dynamic dropdown on Angular 7 at runtime, I am facing an issue where there is whitespace visible in the select options. Despite correctly binding and filling the data, this white space persists. How can I remove this blank area when binding ...

Errors in Visual Studio regarding typescript are often not found by tsc and eslint, causing frustration for developers

Today, after restarting my computer and launching visual studio code, I encountered an unfamiliar error that I've never seen before: https://i.sstatic.net/z1vw5.png I haven't made any changes to my project's code (confirmed by running git ...

Arranging an array of objects by their alphanumeric string property values

Currently, I am facing an issue with sorting an array of objects in TypeScript. The structure of my array is as follows: [ { "title": "Picture3.jpg", "targetRange": "B2", "type": ...

Exploring i18nNext integration with antd table in React

Presently, this is the UI https://i.stack.imgur.com/CMvle.png App.tsx import "./styles.css"; import MyTable from "./MyTable"; export default function App() { const data = [ { key: "1", date: "2022-01- ...

Issues with data texture rendering in the most recent iteration of the third version

I am experiencing a problem with my code that renders a static bitmap in three js. It was working fine in version 110 but stopped working in version 147. I have checked the changelog to see if there were any differences but couldn't find anything. Th ...

"Is it possible in Typescript to set the parameters of a returning function as required or optional depending on the parameters of the current

I am currently exploring Typescript and attempting to replicate the functionality of styled-components on a smaller scale. Specifically, I want to make children required if the user passes in 'true' for the children parameter in createStyledCompo ...

Rendering illuminated component with continuous asynchronous updates

My task involves displaying a list of items using lit components. Each item in the list consists of a known name and an asynchronously fetched value. Situation Overview: A generic component named simple-list is required to render any pairs of name and va ...

Unable to redirect to another page in React after 3 seconds, the function is not functioning as intended

const homeFunction = () => { const [redirect, setRedirect] = useState<boolean>(false); const [redirecting, setRedirecting] = useState<boolean>(false); const userContext = useContext(UserContext); useEffect(() => { const valu ...

Developing an S3 Bucket policy with Pulumi

I am currently working on setting up an S3 bucket and a corresponding S3 policy using Pulumi with TypeScript. However, during the pipeline execution, I encountered the following error in the test stage: expect(received).toEqual(expected) // deep equality - ...