Utilizing Angular @Injectable with a function instead of a class: A step-by-step guide

I am in the process of developing a service for an Angular (2+) application, and I have noticed that all the documentation emphasizes using classes. However, my preference is to write the service as a function.

Here is the code that I want to use (even though it currently does not work):

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

export const AframeMessengerService = Injectable()(function AframeMessengerService() {
    console.log('aframe messenger');
});

Unfortunately, when trying to implement this approach, I encounter the following error in the file where the service is being injected:

Cannot find name 'AframeMessengerService'.

On the other hand, here is the code that does work but does not align with my preferred method:

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

@Injectable()
export class AframeMessengerService {
    constructor() {
        console.log('aframe messenger');
    }
}

Answer №1

Essentially, you are following the correct procedures here:

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

export const AframeMessengerService = Injectable()(function AframeMessengerService() {
    console.log('aframe messenger');
});

Next step is to include this in the module providers:

import { AframeMessengerService } from './a.service';

@NgModule({
  ...
  providers: [AframeMessengerService],
})
export class AppModule {}

Then, inject it as shown below:

import { AframeMessengerService } from './a.service';

@Component({
  selector: 'my-app',
  ...
})
export class AppComponent {   
  constructor(@Inject(AframeMessengerService) s) { }

It is important to remember that when injecting services into AframeMessengerService, you must specify the index of the parameter:

import { Inject, Injectable, Injector } from '@angular/core';

const AframeMessengerService = Injectable()(function AframeMessengerService(i) {
  console.log('aframe messenger');
});

Inject(Injector)(AframeMessengerService, null, 0);
                                         ^^^^^^^

export { AframeMessengerService };

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

How come the `setAllSelected` function does not activate the `listbox.valueChange` events, and what can be done to make it happen?

How come setAllSelected is not triggering the emission of listbox.valueChange? What steps can be taken to ensure that it does emit? import { Component, ViewChild } from '@angular/core'; import { CdkListbox, CdkOption } from '@angular/cdk/lis ...

Encountering a SyntaxError with Angular (8) Http.post() due to an Unexpected token O in JSON at position 0 when trying to parse the

Whenever I attempt to send data to my server, an error is being returned: SyntaxError: Unexpected token O in JSON at position 0 at JSON.parse... Since I'm not utilizing JSON.parse(), could it be that Angular's Http.post() function is automatica ...

Testing the throwing of errors when running Karma by utilizing sinon.spy on global functions like parseInt

I'm currently facing an issue with monitoring the usage of parseInt within my function. This is a Proof of Concept for integrating TypeScript into our company's workflow. I've tried following two different tutorials on testing Sinon, but no ...

Acquire data on the type from the returned outcome of a function

Below is a function that I am working with in the TypeScript playground: function myf(): Record<string, string> { return { prop1: "a", prop2: "b" } } This function is pure and simply returns a dictionary value. My goal is to ext ...

React type error: The argument 'profile' cannot be assigned to the parameter of type 'ComponentType<never>'

I've recently started learning TypeScript and I'm struggling with this particular issue. Below is the code I'm working on. import { IProps, IState } from './types'; class Profile extends Component<RouteComponentProps & I ...

Navigate to a nested page in React router and automatically open a new page whenever there are parameters passed

I am currently using create-react-app to build my project and I am working on implementing dynamic routing. My site has three main pages: Accordion, Movies, and MovieDetail. The Movies page displays a list of movies fetched from swapi. The goal is to have ...

Typescript causing issues with Material-UI theme.mixins.toolbar functionality

Currently, I am utilizing Material-UI to develop a React and Typescript website. The experience has been positive overall, but I am facing a specific issue. I have been trying to implement one of the code examples from their documentation, but unfortunatel ...

Angular2 with Typescript is raising concerns over the absence of specific data types in

I am encountering an issue with the following code snippet: var headers = new Headers(); // headers.append('Content-Type', 'application/json'); headers.append('Content-Type ...

Using Angular's routerLink feature to assign a specific outlet (version 5.0.2)

Despite reading numerous posts on this problem, none of the solutions seem to work for me. I am working with one app module, one routing module, and no additional modules. The issue I'm facing is that... Standard routes can be linked from any compo ...

Understanding Angular 2: The Significance of a Variable Name Ending with ?

Can you explain the significance of a variable name with a question mark? For example: Label?: string I've noticed this syntax in various instances but am unsure about its meaning. ...

Typescript is unable to access the global variables of Node.js

After using Typescript 1.8 with typings, I made the decision to upgrade to typescript 2.8 with @types. When I downloaded @types/node, my console started showing errors: error TS2304: Cannot find name 'require'. The project structure is as foll ...

Transmit HTTP headers when making an HTTP request, similar to using Postman

Encountered an issue with Angular while attempting to send an HTTP POST request, resulting in the following error: Http failure during parsing for service.ts currentUse(SVF){ //let options = {headers: new HttpHeaders({'Content-Type': &apos ...

Pixel 4a users encountering black bottom bars from Android apps

https://i.sstatic.net/PA34b.jpg I'm struggling to remove the black bar at the bottom of my Google Pixel 4a screen with rounded corners. Interestingly, on Huawei phones without rounded edges, the app displays correctly. I've tried various solutio ...

Updating parent object data in child: A step-by-step guide

Currently, I am in the process of creating a custom dropdown component. Within this component, I have a config object that is initialized within the ngOnInit() method. This config object combines both default configurations as well as user-provided configu ...

Issue with Bootstrap Angular dropdown menu malfunctioning within ChildRoute

Recently, I have been working on integrating admin bootstrap html with Angular. As part of this integration, I added CSS and JS files in angular.json as shown below: "styles": [ "src/styles.css", "src/assets/goo ...

Extracting ZoneAwarePromise from Firebase snapshot data

I'm having an issue where I call a function from a service provider in my component. When I call a get function from Firebase, the console outputs a ZoneAwarePromise. What could be causing this problem? Here is the code from xx.component.ts: constru ...

Encountering CircularJSON Error While Creating Angular CLI 7 Project

Recently updated Angular CLI to version 7.1.1 and encountered an issue when trying to create a new project using ng new project-name. The error message displayed is: npm WARN deprecated <a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cf ...

Having trouble with my React component timer not functioning properly

How can I utilize the Header Component as a Clock timer for my webpage to update every second? Despite searching on Google, I couldn't find examples that match my requirements. Why is the tick() function not functioning properly even though there are ...

RxJS: when combined with timer, groupBy operator does not emit any values

Just starting out with RxJS version 6.5.5, I'm encountering an issue with the groupBy operator. Here's a simplified example to showcase the problem. I have a function called retrieveFiles() that retrieves an array of strings. function async ret ...

Guide to adding jquery with typings installation

Need assistance: typings install jquery --global typings ERR! message Unable to find "jquery" ("npm") in the registry. Did you want to try searching another source? Also, if you want contribute these typings, please help us: https://github.com/typings/re ...