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

What are some methods for displaying images retrieved from an API onto an HTML webpage?

Problem: The image is not appearing on my HTML page. How can I fix this issue? Please see below for details. Here are the code snippets I am using to display the image: <div class="col-md-7"> <div class="table-responsive" ...

What is the best way to animate elements so that they move in a circular motion?

My goal is to recreate the image shown in the picture: In case the image is blocked, you can view it here: The picture appears to have only one icon visible, but there are actually 4 icons. The image represents the path that the icons should follow. I&a ...

Switch between two PHP files with a toggle feature using jQuery click event

Need help with toggling between two PHP files - cab.php and d3.php. Toggling within the same file works fine, but encountering issues when trying to toggle from one file to another. function botaod2mostraesconde() { $(".wrapd2").toggle(); $( ...

Angular Reactive Forms may not properly update other inputs when binding a control to multiple inputs

While working with reactive forms, I encountered an issue where accessing the same control in multiple inputs seemed to result in one-way data binding (input-to-model). If I make edits in one input, it updates the model correctly but does not refresh the o ...

Update information in a table row and store it in the database using Ajax

Looking for some guidance with ajax and javascript here. I'm not very proficient in this area, so any help would be greatly appreciated. I have a table on my page where data is displayed like this: <table class="table table-bordered"> ...

React Redux Loading progress bar for seamless navigation within React Router

Currently, I am working on adding a loading bar similar to the one used by Github. My goal is to have it start loading when a user clicks on another page and finish once the page has fully loaded. In order to achieve this, I am utilizing material-ui and t ...

Troubleshooting: Page Unable to Import/Execute Linked JavaScript on WebStorm with Node.js Backend

I've been following W3School's jQuery tutorial, but I'm encountering some issues with importing scripts to an HTML document hosted on a Node server in WebStorm. I have properly installed and enabled the jQuery libraries under Preferences &g ...

Make sure to invoke the initialize function either in the ngOnInit lifecycle hook or

As a beginner in Angular 4, I have a question. What is the difference between calling a method like initializeMyObj() in the constructor versus ngOnInit in a TypeScript file? Thank you for your help! ...

Concurrent Icons on Angular-Chart's Piechart

I recently incorporated angular-charts into my project to make the display of charts easier. Initially, setting up and rendering a pie chart was a breeze following the guidelines I found here. Here's a snippet of the code I used: <canvas id="pie" ...

What is the best way to detect when an option is selected in a Material UI autocomplete component?

Utilizing the autocomplete feature with filterOptions to propose adding a new value: <Autocomplete multiple name="participant-tags" options={people} getOptionLabel={(option) => option.name} renderInput={(param ...

I am having trouble with searching for places using the Google API in my Node

Recently, I've been working on integrating the Google Maps API places feature into my project. Thankfully, I came across an npm module that simplifies the process of connecting it to node. Check out the npm module here! After downloading the module ...

Tips for obtaining a binary file sent through an HTTP:POST request using angular.js

I'm currently working on a project that involves using an Angular.js based viewer with a custom server. My goal is to implement an "execute & download" button. To send the request for execution, I am using an HTTP:POST method with specific headers: ...

"Contrasting the initialization of state in the constructor with managing state

Can you explain the distinction between these two methods of initializing state in ES6 other than their access to props? constructor(props) { super(props); this.state = { highlighted: 5, backgroundColor: '#f3f3f3', ...

variable value remains constant after being updated

Here is the code snippet I am working with: function change(initial) { let a = initial; console.log(a); return [ a, (v) => { a = v; } ]; } const [val, setter] = change("initial"); console.log(val); setter("s&qu ...

Tips for resolving the issue when Chrome is able to load the page but Postman cannot find it

I'm encountering a perplexing situation that is entirely new to me and difficult to comprehend. I find myself unable to decipher what exactly I am witnessing, leading to uncertainty about why it is occurring, not to mention the challenge of determinin ...

Clarification on the syntax for using SWR with Next.js

While following a tutorial, I stumbled upon this code snippet: import useSWR from "swr" import { fetcher } from "./fetcher" export function useFeed() { const { data: feed } = useSWR("/api/feed", fetcher) return { feed } } ...

comprehending the concept of express and mastering its usage

Can you confirm if my understanding is correct? 1) So, when I write this line of code... const express = require(“express”) I am assigning a "Class" to the variable express. 2) And then, when I call this function... express.jason() Am I correctly ...

Configuring route for serving static files in an Express server

I'm completely new to working with express, but I am eager to learn and follow the best practices. My goal is to serve files like CSS or index.html from a folder called 'public'. I have seen examples using .use and .get methods as shown belo ...

Easily submit both FormData and a string in a single function call

I am trying to send data from a form (including a file input and string input) via ajax to an ASP.NET Function. When sending only files, I use the following code: function readURL() { var input = document.getElementById("fileUpload"); var files ...

Dynamic Formatting with Vue JS: Enhancing Phone Number Input

I am working on a form that includes a phone number input field, and I want the formatting of the number to change to a standard telephone number format as the user types. Can someone provide guidance on how this can be achieved using JavaScript and Vue 3? ...