Guide on invoking an Angular 2+ service from a typical TypeScript class (excluding components)

I am currently developing an app using Phaser 3 and Angular 6. I am trying to figure out how to implement Dependency Injection in a typescript class (which is a Phaser Scene) in order to call a service (GameService). Any suggestions on how to achieve this?

export class PlayerConfigScene extends Phaser.Scene {

    constructor(private gameService: GameService) {
        super({
            key: "PlayerConfigScene"
        });
    }

    init() {
        this.gameService.setEnableForms(true);
    } 
}

Here is the code for the GameService

import { Injectable } from '@angular/core';
import { BehaviorSubject } from 'rxjs';

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

  private enableForms : BehaviorSubject<boolean> = new BehaviorSubject<boolean> (false);

  constructor() { }

  public setEnableForms(flag : boolean) {
    this.enableForms.next(flag);
  }

  public getEnableForms() : BehaviorSubject<boolean> {
    return this.enableForms;
  }


}

Answer №1

Consider adding the @Injectable annotation to your non-angular class and including it in a ngmodule for injectability. However, keep in mind that this may not be the best approach.

It appears that there might be some confusion between the concepts used in game development (Phaser) and Angular.

Have you placed the PlayerConfigScene-Object instantiation within an angular component or injectable? Perhaps you could simply inject the necessary service into your component and then create your config object using that service.

If you are integrating your game into an angular project, it is recommended to encapsulate your game within a web component or a dedicated component:

@Component({
  selector: "my-game-wrapper-component",
  template: "<div #myGameWrapper></div>"
})
export class MyGameWrapperComponent implements AfterViewInit {

  @ViewChild("myGameWrapper", { read: ElementRef }) myGameWrapperDiv: ElementRef;

  private game: MyAwesomeGame;

  constructor(private myAwesomeGameService: MyAwesomeGameService) {
    // MyAwesomeGameService must be an injectable angular service
  }

  public ngAfterViewInit(): void {
    this.game = new MyAwesomeGame(this.myGameWrapperDiv.nativeElement, this.myAwesomeGameService);
  }
}

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

Determine if the "type" field is optional or mandatory for the specified input fields in Typescript

I need to determine whether the fields of a typescript type or interface are optional or required. export type Recommendation = { id?: string, name: string, type?: string, tt: string, isin?: string, issuer: string, quantity?: nu ...

Combine the selected values of two dropdowns and display the result in an input field using Angular

I am working on a component that consists of 2 dropdowns. Below is the HTML code snippet for this component: <div class="form-group"> <label>{{l("RoomType")}}</label> <p-dropdown [disabled] = "!roomTypes.length" [options]= ...

What makes ngFor unique in Angular that allows it to not require keys like in Vue and React?

I recently delved into learning Angular a few weeks back. In Vue and React, we typically use a unique key when rendering an array of elements to optimize the rendering process, especially when there are changes in the elements' order or quantity. As a ...

Learn how to set up browser targeting using differential loading in Angular 10, specifically for es2016 or newer versions

Seeking advice on JS target output for compiled Angular when utilizing differential loading. By default, Angular compiles TypeScript down to ES5 and ES2015, with browsers using either depending on their capabilities. In order to stay current, I've b ...

Setting a dynamic routerLink in Angular 2 based on a component's property-value

Recently, I developed a component with a <a> element and a routerLink property that I intended to set from the template in which the component is used. However, when attempting to do so, I encountered an error message stating 'Cannot read proper ...

Angular: Converting this code into a loop - A step-by-step guide

Currently, I am in the process of learning Angular along with its Angular Material UI Framework. Following the installation of dependencies, I created a Material Rank Table using the command below: ng generate @angular/material:table rank-table --module=ap ...

Troubleshooting: Ngx-Echarts Animation Issue at Startup

I've been working on integrating ngx echarts into my Angular app, but I'm facing an issue with the animation during the initial load of the chart. Take a look at this Stackblitz example where you can see that the bars render quickly on initial lo ...

What causes the module declaration in the .d.ts file to fail in an Angular application?

I have recently created a file named global.d.ts within the src folder and it contains the following content: declare module 'ol-contextmenu'; Despite my efforts, placing the file in the root directory or in node-modules/@types did not solve the ...

How to host an Angular 2 application on IIS-10 without using ASP.NET Core

I've managed to create a plane angular-2 application using webpack in Visual Studio 2015 and now I'm looking to deploy it on IIS-10. Since I didn't use the ASP.NET Core template for this project, I need guidance on how to properly deploy thi ...

The attribute 'close' is not present in the 'Application' data type

My approach to importing expressjs looks like this: import { Request, Response, Application, Router } from 'express'; const app: Application = require('express')(); In my typings.json file: "express": "registry:npm/express#4.14.0+20 ...

Retrieve information from two observables without the need for separate subscriptions

After my first observable emits user data from Firebase, I need to make a second call to retrieve additional user information from a different collection. While I can handle these operations separately, the second call should only be triggered once the fir ...

Using TypeScript to separate namespaces

tsconfig.json: ... "module": "none" ... file1.ts: namespace Myns { type Mytype = number } file2.ts: namespace Myns { let x: Mytype ^^^^^^ Error - unable to locate declaration in file1.ts } Why am I encountering an error when trying to us ...

The variable 'cache' is not recognized by Angular

Everything runs smoothly on my local Angular app, but once deployed on Heroku using a Go server, I encounter issues with aot being disabled in the Angular build on Chrome and Opera, particularly on mobile devices using Linux and OSX. However, Safari presen ...

Having difficulty accessing an element within ng-template during the unit test writing process with Jasmine

I am encountering an issue when trying to access a button inside an ng-container in my testing environment. Despite manually setting the value of the ngIf condition to true, the elements inside are not being rendered. Here is what I have attempted so far: ...

Update a specific element within Angular framework

Just starting out with angular and facing a seemingly simple issue that I can't seem to solve despite trying various solutions found on SO. I have created a login component where upon submission, the user is redirected to their profile page. While I a ...

Implementing Login using Google in a Nativescript iOS application: A step-by-step guide

I've been working on implementing Google's ID provider login in Nativescript using the nativescript-social-login plugin. While it works smoothly on Android, I've hit a roadblock with iOS. Following the instructions from the plugin creator, ...

Connect the child content to the form

Are there any methods to connect a projected template (ContentChild) to the form specified on the child, such as adding formControlName after it has been rendered? I am having difficulty in finding relevant information online, possibly due to using incorr ...

How can a property be made mandatory in Typescript when another property is set as optional?

Currently, I am unsure about what to search for in order to fulfill the following requirement. Specifically, I am utilizing the given type for react props: interface ComponentProps { message : string, minValue? : number, minValueValidationMessage? ...

Ways to verify whether a checkbox is selected and store the status in the LocalStorage

Hey there, I'm still new to the world of programming and currently just a junior developer. I have a list of checkboxes and I want to save any unchecked checkbox to my local storage when it's unselected. Below is a snippet of my code but I feel l ...

Creating an Angular component that is flexible in terms of the data type it accepts

Currently, I have successfully implemented a lookup component that is responsible for fetching and filtering a list of users based on the query provided. When a user is selected from this list, they are set as members. This component can be configured with ...