How to add a service to a static function in Angular

After incorporating a logger service into my project, I have encountered an issue with using it in NGXS static selectors. The selectors in NGXS are static methods, which prevent me from accessing the logger service injected via Angular DI.

Are there any elegant solutions to seamlessly utilize the service within the selectors?

constructor(
  public logger: LoggerService
) {}

@Selector()
@ImmutableSelector()
public static get(state: StateModel) {
  // <-- Log via LoggerService
  return state.model;
}

Answer №1

First and foremost, I advise against using a static method to consume your service as it is not considered a best practice.

If you still wish to proceed with using it:

You can simply import your service in the constructor and then utilize it like this:

export class myComponent {
  constructor(private logger: LoggerService) {
     this.constructor.logService = logger;
  }

  public static myMethod() {
   myComponent.logService.log_method()
     .subscribe(
       data => { console.log(data)   },
       error => { console.error(error); }
   );
  }
}

This question has already been addressed here. Access service into a static method in Angular 5. Feel free to do some further research on the topic.

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

Exploring the power of V-for with checkboxes in VueJS

One issue I am facing is related to triggering my save method only when a checkbox is selected or true in Vue JS. I have no problem listing values and saving them to the database using axios, Vue JS, and Spring Boot. However, every time I click the checkbo ...

I am puzzled as to why my DataGrid MUI component is not functioning properly

I am taking my first steps with MUI, the MaterialUI React Component library. After following the installation instructions in the documentation, I am now attempting to integrate the DataGrid component into my React project. My goal is to replicate the fir ...

Accessing a precise div element in a webpage

Currently, I am utilizing Vue.js and Nuxt for my web development. One issue I am facing is related to anchors. Specifically, when I navigate to mysite.com/page1#section1, I want the page to scroll to section1. In my code, I have the following snippet: < ...

How does Angular2 indicate the modification in a segment of Component?

ReactJs utilizes virtual DOM for rendering changes, whereas Angular2 does not have a virtual DOM. However, Angular2 is reactive similar to ReactJS. In Angular2, with any change, the whole component does not need to be modified, only the portion of the co ...

What is the process for modifying a Date type value in JavaScript?

I'm looking to create a graph that illustrates the sun's altitude throughout the day, resembling a sine curve. Users should be able to input a location (latitude & longitude) and a date, and the graph will adjust accordingly. I've incorpora ...

What is the reason for the malfunction of this JavaScript code designed for a simple canvas operation?

I'm having trouble with the code below. It's supposed to display a black box on the screen, but for some reason it's not working properly. The page is titled Chatroom so at least that part seems to be correct... <html> <head> &l ...

Extract information from a webpage using Selenium WebDriver

Currently, I am working on mastering Selenium, but I have hit a roadblock that I need assistance with. My task is to gather all the betting information for games from the following link and store it into an array. Given my limited experience with HTML an ...

Tips for verifying the response and status code in Angular 8 while uploading a file to an S3 Presigned URL and receiving a statusCode of 200

Looking to Upload a File: // Using the pre-signed URL to upload the file const httpOptions = { headers: new HttpHeaders({ 'Content-Disposition': 'attachment;filename=' + file.name + '', observe: 'response' }) }; ...

Tips on expanding the dimensions and incorporating more members in a radar graph's Chartjs tag

I need to make some adjustments to the font size and color in a radar chart. Specifically, I want to change the name on the side of each data point. I have already tried adjusting the legend labels using the following code: options={{ ...

The Cordova InAppBrowser plugin has not been properly set up

After running cordova plugin list, I noticed that the InAppBrowser plugin is listed. However, when I try to run my code on an android device, I receive this message in the console via Chrome Remote Debugger: Native: InAppBrowser is not installed or you ar ...

The middleware is causing disruptions in the configuration of redis and express

I've recently started using Redis and I'm facing an issue with my middleware 'cache' function that seems to be causing problems in my code. Everything works fine without it, the data displays correctly in the browser, and when I check f ...

tips on launching a pre-existing react native project

Trying to run a project downloaded from someone else can be quite challenging. I encountered some issues where the project just wouldn't start, and now I'm completely stuck. Can anyone help me out? https://github.com/sunlight3d/react_native_v0.4 ...

What are the best ways to keep a django page up to date without the need for manual

Currently, I am in the process of developing a Django website focused on the stock market. Utilizing an API, I am pulling real-time data from the stock market and aiming to update the live price of a stock every 5 seconds according to the information pro ...

Implementing ng-if with asynchronous functions: A step-by-step guide

The objective here is to display an image in a template only if the ratio of its dimensions is greater than 2. <img class="main-img" ng-if="showImage($index)" ng-src="{{item.img}}"> Implementation: $scope.showImage = function(index) { var img ...

Collaborative service utilization in Angular 2

My goal is to create a shared service for my app. import { Injectable } from '@angular/core'; @Injectable() export class SharedService { testService() { console.log('share!'); } } However, when I attempt to inject this shared ...

I am experiencing difficulties with implementing Angular material components in my project

I recently encountered an issue while trying to integrate angular material into my project. Despite importing the MatFormFieldModule, I received the following error: ERROR in src/app/login/components/login/login.component.html:2:1 - error NG8001: &apo ...

Enabling Event bus suggestions for Typescript: A step-by-step guide

Hello, I've encountered an issue while attempting to add types for the TinyEmitter library. Specifically, I need to define two methods. First: addEventListener(e: string, (...args: any[]) => void): void; Second: emit(e: string, ...args: any[]): vo ...

What is the proper method for terminating an Express app.all?

Here's a snippet of my code where I utilize the app.all method. In this scenario, I am invoking the fetchBuildings function based on the building ID or hash provided in the URL. Subsequently, I am assigning values to the title, description, and image ...

What is the best way to include a non-Typed Angular service in a TypeScript class?

I have a module and service in Angular that were originally developed without TypeScript, like this: MyModule = angular.module('MyModule', ['dependency1', 'dependency2']); MyModule.factory('MyService', ['$other ...

Exploring how to utilize class properties within Angular templates

I am facing an issue with using a template property in Angular. Despite my attempts, it is not functioning as expected and I am unable to pinpoint the cause of the problem. To illustrate, I have set up a demonstration here: https://github.com/Fulkerson/an ...