The 'createGame$' property is not found on the 'GameService' object

A new GameService has been crafted with the implementation of the ServiceInterface:

export interface ServiceInterface {
  emitter$;
  actions: any[];
  [action: string]: any;
}

export class GameService implements ServiceInterface {

  constructor() {
    super();
    this.actions = [
      { name: 'createGame$', handler: this.createGame.bind(this) }
    ];
    this.initializeActions();
  }

  initializeActions() {
    // creating action subject and subscribing handlers for each action
    if (this.actions) {
      for (let action of this.actions) {
        this[action.name] = new Subject();
        this[action.name].subscribe(action.handler);
      }
    }
  }

The issue arises when trying to add properties dynamically in the GameService, like this.createGame$. An error message pops up:

Property 'createGame$' does not exist on 'GameService'

It was assumed that using [action: string]: any; within the interface would enable dynamic property addition - what could possibly be missing?

Answer №1

When you are creating actions, the goal is to connect createGame to an action that has not been created yet.

this.actions = [
    { name: 'createGame$', handler: this.createGame.bind(this) }
];

It might be more effective to create the handlers in registerActions instead because at that moment, you have a reference to the current action.

 constructor(){
    this.actions = [
        {name:'createGame$', handler:null}
     ];
     this.registerActions();
 }

 registerActions(){
    //current class instance. includes createGame$ property
    console.log('registerActions(): ', this); 

     if(this.actions){
        for (let action of this.actions) {
            //set handler here rather than in the constructor to bind
            // to the current action
            action.handler = this.createGame.bind(action); 

             this[action.name] = new Subject();
             this[action.name].subscribe(action.handler);
         }
     }
 }

 createGame(){
    // in this context, 'this' refers to the current action
    console.log('createGame(): ', this);
 }

View plunker demo

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

Can you explain the distinction between implementing tab content styles?

My method for displaying tab content is as follows: <mat-tab-group> <mat-tab label="First"> <ng-template matTabContent> The First Content </ng-template> </mat-tab> </mat-tab-group> What sets this apar ...

Comparing NativeScript and Flutter

Currently diving into the world of Native Script with Angular, I am fascinated by the code sharing capabilities that allow me to work on both web and mobile applications. However, a lingering question in my mind is why Google chose to develop Angular for ...

What is the best way to retrieve the value of an input field in React when incorporating Material UI components?

I am working with a few radio input components that have been imported from material Ui react. Each radio input is wrapped in a FormControlLabel component. <FormControlLabel onClick={checkAnswerHandler} value={answer} control={<Radio color=&quo ...

Node module for Nativescript angular project that enables multi select dropdown or picker functionality

Does anyone know of a Node NPM module for creating a multi-select dropdown in NativeScript Angular? I've searched through many plugins in the NativeScript marketplace, but haven't been able to find one that fits my needs. I need the plugin to wo ...

TypeScript compilation error caused by typing issues

My current setup includes typescript 1.7.5, typings 0.6.9, and angular 2.0.0-beta.0. Is there a way to resolve the typescript compile error messages related to the Duplicate identifier issue caused by typings definition files? The error message points ou ...

Is it best practice to encapsulate providers within an Angular module?

My list of service providers continues to grow: app.services.ts: providers: [ RegistrationService, LoginService, LoginPageGuard, LoggedInGuard, VerifiedGuard, LoggedInAndVerifiedGuard, UnverifiedGuard, NotLoggedInGuard ], When dealing with modules ...

tips for accessing form data in Angular 4 when dealing with an array of objects

I've encountered an issue with my Angular 4 form code. It's not working and I'm getting the following error: TypeError: Cannot read property '0' of undefined.. Can anyone help me troubleshoot this problem? <form (ngSubmit)="pro ...

Run a script in a newly opened tab using the chrome.tabs.create() method

Struggling with executing a script using chrome.tabs.executeScript() in the tab created with chrome.tabs.create()? Despite searching for solutions, nothing seems to be working as expected. Check out my current code below: runContentScript(){ c ...

What is the proper method for specifying the path to my index.tsx file within a React application?

After using npx create-react-app my-app --template typescript to generate my React app, I decided to reorganize the files by moving them to /src/client and relocating my Express backend to /src/server. However, upon running the relocated React app, I encou ...

bespoke session with Next.js using Next-Auth

I encountered an issue while migrating my JS file to TSX. What I am trying to do is sign in with credentials and customize the session user to my user data. // api/auth/[...nextauth].js import NextAuth from "next-auth"; import Providers from &qu ...

Is it possible to share screens via socket.io without the need for selecting a screen prompt?

I am looking to select my screen and share it on a socket.io server without any pop-up form the browser using navigator.mediaDevices.getDisplayMedia({ video: true }).then((stream: MediaStream) => { ...

What is the process for configuring PhpStorm to sync with TypeScript tsconfig.json in .vue files?

Vue.js (webpack + vueify) with TypeScript is my current setup. The ts configuration appears to be functioning, but only in .ts files. For instance, in tsconfig.json: "compilerOptions": { "strictNullChecks": false, So strictNullChecks works as expect ...

"CanDeactivate Implementation Failure: Why isn't the Generic Function Being Called

I am currently working on implementing a guard to prevent users from navigating to the login page once they have authenticated themselves. This guard should apply to all page components in my app except for the login page. Below is the code snippet I am u ...

Sharing information between sibling components in Angular

https://i.sstatic.net/Pn74N.png The image above showcases my Angular 2 application, where the Main component is divided into two child components: "FromComponent" and "ToComponent". The "FromComponent" displays a list of items with a checkbox beside each ...

At compile time, Typescript runs smoothly, but errors may arise during runtime

Currently, I am delving into learning Typescript and have encountered a snag in my code. Despite searching extensively for a solution, I have been unable to find any relevant material pertaining to my issue. Below is the code snippet in question: <code ...

How to specify in TypeScript that if one key is present, another key must also be present, without redundantly reproducing the entire structure

In my code, I have a custom type defined like this (but it's not working): type MyType = | { foo: string; } | { foo: string; barPre: string; barPost: string; } | { foo: string; quxPre: string; qu ...

The styles and scripts in Angular.json are not functioning properly

Attempting to integrate Bootstrap into my Angular project, but encountering issues with Scripts and Styles in angular.json After trying to copy the path from the folder, I keep getting errors! "styles": [ "C:\AngularProjects\project1\no ...

Issue with NGXS Selector Observable not reflecting updated state

My issue is that when I update the state, my selector does not pull the new values. I have defined the selector in my state and I can see the state values getting updated. However, the selector in my component is not fetching the latest values. Even though ...

Splitting the string into individual characters using string.split("").map may cause layout issues on small devices

Shoutout to @pratik-wadekar for the amazing help in creating a working text animation. However, I encountered an issue when testing it on various screen sizes and mobile devices - the animated word plants breaks into pieces like PLA on one line and NTS on ...

Utilize the class or interface method's data type

In the context of a child component calling a callback provided by its parent, this situation is commonly seen in AngularJS. As I am utilizing TypeScript, I aim to implement strong typing for the callback in the child component. Here is the initial stat ...