Using Angular DI to inject a specific token value into a provider factory

Can an InjectionToken be injected into a factory provider?

This is what I have implemented:

export const HOST_TOKEN = new InjectionToken<string>("host");

let configDataServiceFactory = (userService: UserService, host: string) => {
    return new Config("host", 8080, userService.getUser(), userService.getPasswd());
};

export let configDataServiceProvider =
{
    provide: CONFIG_API,
    useFactory: configDataServiceFactory,
    deps: [UserService, HOST_TOKEN]
};

In my module:

@NgModule(
  providers: [
    {provide: HOST_TOKEN, useValue: "allianz-host"},
    configDataServiceProvider
  ]
)

However, Angular seems to be injecting the value "host" instead of "host-allianz" in configDataServiceProvider.

Any suggestions on how to fix this?

Answer №1

A method to achieve this is by using the @Inject decorator as shown below. This allows you to extract the necessary dependency from the DI container.

let configDataServiceFactory = (userService: UserService, @Inject(HOST_TOKEN) host: string) => {
    return new Config(host, 8080, userService.getUser(), userService.getPasswd());
};

Another option to consider is accessing all registered InjectionToken's from the application's Injector. This can be done by calling the get method on the injector instance and providing the name of the InjectorToken.

export const HOST_TOKEN = new InjectionToken<string>("host");

let configDataServiceFactory = (userService: UserService, injector: Injector) => {
    let host = injector.get(HOST_TOKEN); //retrieve token from injector
    return new Config(host, 8080, userService.getUser(), userService.getPasswd());
};

export let configDataServiceProvider =
{
    provide: CONFIG_API,
    useFactory: configDataServiceFactory,
    deps: [UserService, Injector]
};

Find more information 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

What is the process of determining if two tuples are equal in Typescript?

When comparing two tuples with equal values, it may be surprising to find that the result is false. Here's an example: ➜ algo-ts git:(master) ✗ ts-node > const expected: [number, number] = [4, 4]; undefined > const actual: [number, number] ...

What purpose does the # symbol serve in Angular when interpolating values?

Here is an example provided from the following link: https://angular.io/guide/lifecycle-hooks export class PeekABoo implements OnInit { constructor(private logger: LoggerService) { } // Implementing OnInit's `ngOnInit` method ngOnInit() { this ...

Does this Spread Operator Usage Check Out?

Upon reviewing Angular's API documentation, I came across the declaration for the clone() method in HttpRequest as follows: clone(update: { headers?: HttpHeaders; reportProgress?: boolean; params?: HttpParams; responseType?: "arraybuffer" ...

What is the best way to pass a conditional true or false value to React boolean props using TypeScript?

I am currently utilizing the Material UI library in combination with React and Typescript. Whenever I attempt to pass a conditional boolean as the "button" prop of the component, I encounter a typescript error stating: Type 'boolean' is not assi ...

Unable to personalize map controls in OpenLayer mapping system

Having trouble styling custom map controls with CSS selectors .ol-zoom-in and .ol-zoom-out. Any suggestions on how to customize them? export class CustomMapControlsComponent implements OnInit { map: Map | undefined; constructor() {} ngOnInit() ...

Determine the category of a nested key within a different type

I'm currently utilizing graphql-codegen which generates types in the following structure: type Price = { onetime: number; monthtly: number; }; type CarModel = { price: Price; name: string; }; type Car = { model: CarModel; someOtherAttri ...

Backend serving an Angular application with Spring Security configuration

As I develop a web application using Angular for the frontend and Java for the backend (using technologies like Spring Boot, Spring Security, JWT), I am facing some confusion on how these components should work together. During development mode, everythin ...

Error: Interface declaration for _.split is missing in the Lodash.d.ts file

For my current typescript project that heavily relies on Lodash with lodash.d.ts, I've encountered an issue with the _.split function not being implemented yet. It's listed under the 'Later' section in the .ts file. I need to find a wo ...

Encountering difficulties compiling Angular project

Error : PS C:\toolbox\intern-page> tsc C:\toolbox\intern-page\src\app\homepage\homepage.component.ts node_modules/@types/core-js/index.d.ts:829:20 - error TS2304: 'PromiseConstructor' cannot be foun ...

retrieve data from the server

Currently, I am delving into the world of Angular with ASP.NET Core 3.0 and still relatively new to it. Here's my scenario - I have a function that is able to save PDF files in a specific folder called "Resources\PdfFiles" within the ASP.NET back ...

Using an array to enforce form validation rules in Angular, including prohibited form values

I am currently developing a basic Angular form with specific validation requirements: The input must not be left empty The input cannot match any of the values stored in the array forbiddenValues. While I understand how to implement the required validat ...

Steps for including a component in a loop using Angular 6

I'm working on a component that contains two input fields. The goal is to have a row pop up every time the user clicks on the add button, with all the inputs eventually being collected in an array of objects. For example, the component template looks ...

Encountering an issue when using the Google authentication provider with Next.js version 13

I am currently working on integrating next-auth with the Google provider and Prisma in my Next.js application, but I encountered the following error: Error: Detected default export in '/MyProject/foodbrain/app/api/auth/[...nextauth]/route.ts'. Pl ...

Web performance issues noticed with Angular 8 and Webpack 3.7 rendering speed

My web application is currently taking 35 seconds to render or at least 1.15 seconds from the initial Webpack start. I've made efforts to optimize Webpack, which has improved the launch speed, but the majority of time is consumed after loading main.j ...

Angular and the feature of contenteditable

I've been searching for a solution online, but I haven't been able to find any clear way to work with contenteditable events in Angular 6/7. It seems like Angular has a complicated approach to this issue and the feature doesn't appear to be ...

Tips for effectively utilizing react-test-renderer/shallow in a TypeScript environment

Looking to utilize react-test-renderer/shallow for testing my react component. However, when I try to import ShallowRenderer from 'react-test-renderer/shallow'; tsc throws an error stating that 'Module '"/Users/dulin/workspace/react-t ...

Changing a table cell's value when a button is clicked using Angular

I'm working with a bootstrap table that includes a button and a textbox above it. After entering a number in the textbox and clicking the generate button, I need to update the "Bill Amount" column for each row with the value from the textbox. How can ...

Patience is key: Techniques for waiting on service responses in Angular 2

Here is the code snippet I have been working on: canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): boolean { let isAuthenticated: boolean = false this.authServiceLocal.isAuthenticated().then(response => isAuthenticated = r ...

Executing the serve command in an Angular project necessitates a project definition, which unfortunately could not be located

An issue has arisen with the application I developed (angular2 nodejs). Upon attempting to open it, I encountered the following error message: The serve command needs to be executed within an Angular project, however a project definition could not be lo ...

Creating multiple dynamic dashboards using Angular 4 after user authentication

Is there a way to display a specific dashboard based on the user logged in, using Angular 4? For example: when USER1 logs in, I want dashboard 1 to be visible while hiding the others. Any help would be greatly appreciated... ...