Using Angular's useFactory method to transmit values to a service

I am currently working on implementing a service in the following manner:

my-module.module.ts

import { NgModule } from '@angular/core';
import { MyService} from './my-service.service';

@NgModule({
  providers: [
    {
      provide: MyService,
      useFactory: () => new MyService(2),
    },
  ],
})
export class MyModule {}

my-service.service.ts

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


@Injectable()
export class MyService {
  constructor(
    private n: number
  ) {
    console.log(this.n);
  }
}

However, I encountered an error message:

Error NG2003: No suitable injection token for parameter 'n' of class 'MyService'. Consider using the @Inject decorator to specify an injection token.

To resolve this issue, a workaround involving Inject('') was suggested, although it seems unconventional and is not documented in the official documentation:

my-service.service.ts

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


@Injectable()
export class MyService {
  constructor(
    // Unconventional fix
    @Inject('') private n: number
  ) {
    console.log(this.n);
  }
}

The Angular version being utilized is 13.3.11

Answer №1

One option is to use the useValue property:

@NgModule({
  providers: [
    MyService {
      provide: "propertyName",
      useValue: "2",
    }
  ],
})

@Injectable()
export class MyService {
  constructor(
    @Inject('propertyName') private value: string
  ) {
    console.log(this.value);
  }
}

Learn more about Angular dependency injection providers here

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

Issue with Implicit Import Feature in TypeScript 2.1 Not Functioning as Expected

I was eagerly anticipating the release of TypeScript 2.1.4, as one of the major reasons my team decided to use TS was the convenience of importing installed modules without needing to search for or create type definitions, thanks to implicit any imports. H ...

Leverage a personalized column within a for loop in an Angular template

I have created the code below: table.component.html <div class="mat-elevation-z8"> <table mat-table [dataSource]="tableDataSrc" matSort class="mat-elevation-z8"> <ng-container *ngFor="let col of tableCols"> <ng-container ...

What is the best method for retrieving multiple values as an array from an observable using rxjs?

I'm struggling with a button event: checkAnswer() { const btn = this.btns.map(btn => btn.nativeElement); this.nextAskSub = fromEvent(btn, 'click').pipe( *// I'm not sure if my approach is correct. Can I achieve this? //* [plu ...

Dynamically Loading Inputs into Components in Angular

I have developed a function that enables me to import components from a core Angular application into multiple libraries. The function returns the component as a DOM element, which I then append to the corresponding child libraries. Now, I am facing an iss ...

Designing the presentation of two overflowing text containers positioned next to each other

Hey there, I'm currently working on styling something that shows both the user's username and the title of an item on the same line, similar to how it's done on GitHub: username / title I want to make sure that if the combined width of the ...

The use of window.Image() is ineffective when working with TypeScript and React

In my React project, I am utilizing the KonvaJS library. You can find more information about it here. To display an image using JavaScript/React, I have implemented the following code: componentDidMount() { const image = new window.Image(); ima ...

Defining types for functions that retrieve values with a specified default

My method aims to fetch a value asynchronously and return it, providing a default value if the value does not exist. async get(key: string, def_value?: any): Promise<any> { const v = await redisInstance.get(key); return v ? v : def_value; } W ...

Is the naming convention for parameterized types (T, U, V, W) in Generics adhered to by Typescript?

Is TypeScript following the same naming convention for parameterized types as other languages like C++ and Java, using T,U,V,W, or is there a mixed usage of conventions? In the TS 2.8 release notes, we see examples like: type ReturnType<T> = T exten ...

What is the method for importing a JavaScript file into my TypeScript file?

Recently, I've encountered an issue while working with Typescript and angular 2. I have built an EncryptionService that looks like this: import {Injectable} from 'angular2/core'; import './lib/hmac256-enc64'; @Injectable() ...

Launch the flutter application's web browser and seamlessly navigate back to the app

Currently, I am in the process of developing a mobile application with Flutter, alongside a web version using Angular and Node.js for the backend. I have found myself in need of a unique workflow that involves redirecting users to the web application duri ...

Encountering a Typescript TypeError in es2022 that is not present in es2021

I'm attempting to switch the target property in the tsconfig.json file from es2015 to es2022, but I am encountering an error while running tests that seem to only use tsc without babel: Chrome Headless 110.0.5481.177 (Mac OS 10.15.7) TypeError: Can ...

"Pairing AngularJS 2 with Vaadin for a winning combination

Good day, I'm currently following a tutorial but encountering some challenges with integrating Vaadin and Angularjs2 into my Joomla Backend project. The error message I am facing is as follows: polymer-micro.html:196 Uncaught TypeError: Cannot read ...

Sharing information among components in Angular

This is the structure of my page: https://i.sstatic.net/2NgrN.png app.component.html <app-header></app-header> <router-outlet></router-outlet> <app-footer></app-footer> The data loading process occurs in the app.com ...

Utilizing Angular's intelligent dichotomy of (container) and (presentational) components, integrating conditional logic, and effectively passing inputs throughout the

Imagine you have two simple components, A and B. Component C will only display either component A OR B, which is controlled by smart component D. D (smart) | C (simple) / \ A B (both simple) Both components A and B have 10 inputs each. Ther ...

Error: Attempting to access the 'user' property of a null value

I need help passing a unit test for my isAdmin() function. The function is supposed to return a role, but I keep getting an error that says 'user' cannot be read. I think the issue lies in how I am handling the user information provided by curren ...

When utilizing the Angular 9 package manager to install a package with the caret (^) in the package.json file, it may

Within my package.json file, I have specified the dependency "@servicestack/client":"^1.0.31". Currently, the most updated version of servicestack is 1.0.48. On running npm install on my local environment, it consistently installs vers ...

Contrasting characteristics of class members in JavaScript versus TypeScript

Typescript, a superset of Javascript, requires that Javascript code must function in Typescript. However, when attempting to create class members in a typescript file using the same approach as Javascript, an error is encountered. CODE :- script.ts (types ...

What is the process for inheriting a parent component's template in Angular 4?

Is there a way to inherit the template from a parent component in Angular 4 without overriding it completely? Many tutorials show how to override the parent component's template like this: import { Component } from '@angular/core'; import { ...

Angular 10 - Timezone Detection and Interactive Calendar

I am encountering a major issue with the Angular DateTimePicker and TimeZone functionality. I need to dynamically switch the TimeZone at runtime in my component. Every date displayed on the frontend must be converted, while every date sent to the backend n ...

Using AWS StepFunctions to add a prefix to an input string

How can I use TypeScript and CDK to create a task that prefixes one specific field in the input while leaving the rest unchanged? Input: { "field1": "foo", "field2": "bar" } Desired output: { "field1" ...