Include the providers after declaring the AppModule

When it comes to Angular 2+, providers are typically registered in the following manner:

// Using the @NgModule decorator and its metadata
@NgModule({
  declarations: [...],
  imports: [...],
  providers: [<PROVIDERS GO HERE>],
  bootstrap: [...]
})
export class AppModule { }

However, I am interested in setting up application-scoped providers separately from this declaration location.

My current situation involves utilizing NSwag to automatically create service clients for my entire Web API, and I wish to dynamically add these generated service clients as providers. The challenge lies in finding a way to accomplish this task, especially given that @NgModule is an attribute that applies to the AppModule class itself.

Do you happen to know if achieving this separation of concern is actually feasible?

Answer №1

Every DI provider must be included in the module during compile time.

Angular dependency injection operates using Typescript type symbols / tokens, making it impossible to achieve the same functionality in Javascript post compilation.

To add a provider dynamically at compile time, you can follow this example:

import { Load, SomeToken } from '../someplace';


@NgModule({
  declarations: [...],
  imports: [...],
  providers: [
    {
      provide: SomeToken,
      useValue: Load(someVariable)
  ],
  bootstrap: [...]
})
export class AppModule { }

and then define the Load function and token elsewhere:

export const SomeToken = new OpaqueToken<any>('SomeToken');

export const Load = (someVariable) => {
  // logic to return an @Injectable here. Variable provided could be something like an environment variable, but it has to be exported and static
}

This method limits the need for information to be known during compile time. An alternative approach is to either globally import all required providers throughout the app regardless of circumstance and lazily load components with the necessary provider injected when needed, or create a provider that can perform the logic irrespective of dynamic criteria. One suggestion is to create another service that utilizes the first service and resolves things based on dynamic criteria.

If only API information is required (such as URLs), one option is to fetch URL information from a config.json file or through an API call, and inject those values into the service so the calls and tokens remain consistent but with different values. For more details on achieving this, refer to this link.

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

Encountering issues with loading Angular formControl

I've been going through an Angular tutorial on forms, which you can check out here. In my 'datasources.component.html' file, I have the following code: <form [formGroup]="queryForm"> <label>Query: <input type="text" formCont ...

javascript Unable to execute function in Internet Explorer 11

I'm experiencing an issue where this script works in Google Chrome but not in IE 11. Can anyone explain why?: <script type="text/javascript"> window.onload = function () { var ammount = document.getElementById('ammount'); var price = ...

Tips for adjusting the horizontal position of a grid item within a map() loop

I am trying to align the text in my Timeline component from Material Ui always towards the center of the timeline. The TimelineContent contains Paper, Typography (for title and description), and an image. Currently, I have multiple TimelineContent element ...

A guide on smoothly navigating to the desired row in a gridview using Asp.net

Currently, I am developing a project using ASP.net and C# technology. In my application, I integrated a GridView that contains multiple rows. Within the grid, there is a text box and a search button available. The columns displayed in the grid are Id and ...

What could possibly be causing the "Unexpected token (" error to appear in this code?

Sorry if this appears as a typo that I am struggling to identify. My browser (Chrome) is highlighting the following line <a class="carousel-link" onclick="function(){jQuery('#coffee-modal').modal('show');}">Book a coffee</a> ...

Testing Vue Component with Cypress revealed that the function getActivePinia was triggered without an active Pinia instance

Below are the code snippets I'm working with: Test.vue <template> <button v-show="store.common == 'hi'" @click="func"> hello world </button> </template> <script setup> import {mainS ...

Highcharts failing to connect the dots with lines between data points

UPDATE: After some investigation, it turns out that the issue stemmed from inconsistent intervals. By following the solution outlined in this post, the problem was easily resolved. I have implemented highcharts to create a chart, where the initial data po ...

Setting up Laravel with pjax

For the first time, I am experimenting with using pjax in combination with Laravel to enhance page loading speed. Since I am not well-acquainted with this technology yet, I have integrated this package into my project. Everything appears to be functioning ...

Adjusting the vertical dimension of an Angular 17 Material Dropdown Field?

Check out this demo where I'm exploring ways to decrease the height of the select field. Here's the code snippet: <mat-form-field appearance="outline"> <mat-label>Toppings</mat-label> <mat-select [formControl]=& ...

Typing the url in the address bar when using Angular's ui-router

Two distinct states are present: .state('test', { url: '/test', templateUrl: 'js/angular/views/test.html', controller: 'UserController', }) .state('test.list', { url: ' ...

NPM Alert: Outdated lockfile detected The package-lock.json file appears to have been generated using a previous version of NPM

package-lock.json causing issues when upgrading from Angular 9 to 10 Is there a way to generate a new package-lock.json file and successfully upgrade Angular 9 to 10? I'm looking to update from Angular 9 to 10 and troubleshoot the error related to p ...

The error message "React is not defined" is commonly encountered when using React Native Storybook with

While attempting to configure React Native with Storybook, I encountered an issue when importing a .tsx component. The error displayed was: React is not defined ...

What is the best way to configure the default entry point for a package.json file in a React

I'm having trouble with the default export in my package.json file. when I try to import: import { Component } from 'packagename/'; // size 22kb or import { Component } from 'packagename/dist' // size 22kb; but import { Component ...

proper method for adding line breaks in json

I am experiencing difficulty in creating a line break using \r\n with the given payload on this particular screen. I am on a quest to determine the correct json payload that needs to be dispatched to the frontend in order for it to register as a ...

Tips for locking the button in the navigation bar while scrolling

I noticed that when I have 6 fields in my navbar, with 5 of them being links and one as a dropdown, the scrolling of the page causes all fields to remain fixed except for the dropdown field.Check out this image description for reference https://i.stack.im ...

ReactJS displays a collection of items stored within its state

I encountered an issue while trying to display a list of items in my React app with the following error message: Objects are not valid as a React child (found: [object MessageEvent]). If you meant to render a collection of children, use an array instead. ...

Cannot update VUEjs array following the splice operation

My array is only updating in the console and not in the DOM. I've already tried using :key but it's still not working. Here is my code: <div style="margin-top: 5px;" v-for="(file, index) in editedItem.file_name" ...

What is causing the geolocation heading to remain "null" on Android devices when using Chrome?

Recently, I developed a compact geolocation watch using the following code snippet: navigator.geolocation.watchPosition( this.updateLocation.bind(this), this.errorLocation.bind(this), {enableHighAccuracy: true} ); The function updateLocation ...

Retrieve the most recent score of authorized players using the Google Game API and Node.js

How can I display the last score of a specific game using the Google Play Game API? For example, I am looking to retrieve the latest scores of authenticated users playing "Rush Fight" with NodeJS. Any suggestions on how to achieve this? ...

Is there a way to remove a certain child category post from appearing in a parent category?

I'm having trouble with displaying related posts by category while excluding a specific category. I've tried different methods but none seem to work, and I'm not sure how else to approach this issue. <?php $categories = get_the_terms ...