Setting up the module within the shared module starting from the root directory

One interesting challenge I'm facing is how to hide the dependency of a shared module from the root module, while still allowing the root module to configure it through the shared module. Here's an example:

In my SharedModule.ts file:

@NgModule({
  imports: [
    //I want the root module to configure this without directly importing it
    ConfigModule.forRoot({
      provide: ConfigLoader,
      useFactory: (configFactory),
      deps: [HttpClient]
    })
  ],
  declarations: [MyComponent],
  exports: [MyComponent],
  providers: [HttpClient]
})
export class SharedModule { }

Now in my AppModule.ts file:

@NgModule({
  declarations: [
    AppComponent
  ],
  imports: [
    BrowserModule,
    HttpClientModule,
    AppRoutingModule,
    SharedModule, //I need to configure ConfigModule from here
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }

I've tried using ModuleWithProviders (static forRoot) but it doesn't expose imports. Any thoughts or suggestions on how to achieve this?

Answer №1

export class ModuleExample {
  static initialize(config: CustomConfig): ModuleWithProviders {
    // Display user configuration
    console.log(config);
    return {
      ngModule: ModuleExample,
      providers: [ExampleService, {provide: 'config', useValue: config}]
    };
  }
}
@Injectable()
export class ExampleService {

  foo: any;

  constructor(@Inject('config') private config:any) {

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 best way to implement Angular 2 slash routes in conjunction with Node Express?

I have defined some routes in my App component: @routeConfig([ { path:'login', name: 'Login', component: Login }} Additionally, I have a basic node express loader set up: var express = require('express'); var ...

The issue arises when trying to use the map function on ctorParameters, which

I recently installed Angular2CLI from Bitbucket. After running npm install, ng build, and ng serve, I encountered an error when trying to access localhost:4200. Uncaught TypeError: ctorParameters.map is not a function at ReflectionCapabilities.paramet ...

Exploring data binding in Angular 2 through ngModelChange

When it comes to data binding, achieving property and event binding is possible with $event representing the entered value below: <input [ngModel]="username" (ngModelChange)="change($event)"> But what does the following code snippet mean? <inpu ...

Highlighting DOM elements that have recently been modified in Angular

Is there a simple way to change the style of an element when a bound property value changes, without storing a dedicated property in the component? The elements I want to highlight are input form elements: <tr field label="Lieu dépôt"> ...

The shared service is experiencing difficulties in transferring data to the following component

I have developed two components along with a shared service. My goal is to transfer data from one component to another, but I am encountering an issue where the object appears empty. Below is the code for the first component: import { Component, OnInit } ...

Issue with ngModel being undefined after data has finished loading in Ionic 3

As a newcomer to Angular 4, I've been struggling to find a solution for a seemingly simple issue related to an Ionic app. Whenever a user logs in, the entire user object is saved to localStorage. Despite trying various plugins, I settled on a straight ...

Error message "Attributes are not supported in JSX element class when using React with ApolloProvider and Typescript"

Hello there, I'm fairly new to Typescript, so I hope I'm not missing something obvious here. :) Recently, I've been working on incorporating Apollo into my Typescript project to interact with a GraphQL API. You can find the documentation I& ...

Angular Dynamic Form Troubles

Recently, I followed a tutorial from https://angular.io/guide/dynamic-form to create a dynamic angular form. So far, everything has been working smoothly. However, I am now facing a challenge as I try to implement a question type where users can add more i ...

Sending optional data in Angular routesIn Angular, you can include additional

In my project utilizing angular 5, I have a lengthy routing file: const homeRoutes: Routes = [ { path: 'home', component: HomeComponent, children: [ { path: 'registration', component: RegistrationCompone ...

Building a user interface with React JS to iterate over an array using the map function, passing each item as a parameter

I have been instructed to create an interface for my code related to .map, but I am unsure about how to proceed. I have been searching for examples without any luck so far. I have isolated the specific code with ###. Any assistance in this matter would be ...

Remove a specific NgRx node using LazyLoading technique

I am currently developing an Angular 9 application utilizing NgRx with lazy loading functionality. Upon initial app load, the state appears as follows: https://i.sstatic.net/C7C7P.jpg However, when navigating to the '/account-config' route, th ...

Tips on how to properly format a DateTime String

I need help with formatting a DateTime string retrieved from an API where it is in the format of YYYY-MM-DDTHH:MM:SS +08:00 and I want to change it to DD-MM-YY HH:MM getDataFromApi(res) { this.timestamp = this.timestamp.items[0].timestamp; console ...

Inject Angular environment variables into compiled static Angular files within a Spring Boot application

Currently, I am utilizing Angular and Spring Boot for the development of a website project. During deployment, we execute the command ng build --output-path=../spring-boot-project/src/main/resources/static" in Angular to generate a static folder withi ...

Typescript - Custom Object type that is always terminated by either a string or a number

Does TypeScript have a way to create a versatile object that can have multiple nested levels but always end with either a string or number property? interface GenericObject { [key: string]: string | number | GenericObject | GenericObject[]; } const obje ...

Avoid using <input oninput="this.value = this.value.toUpperCase()" /> as it should not convert the text displayed on the "UI", rather it should send the uppercase value

<input oninput="this.value = this.value.toUpperCase()" type="text" id="roleName" name="roleName" class="form-control width200px" [(ngModel)]="role.roleName"> Even though the UI is changing ...

Retrieve a collection of duplicate objects and choose the one with the most recent date

Having trouble figuring out how to solve a problem with manipulating an Object Array called items. The array contains four items in total. const items: any[] = await sp.web.lists.getByTitle("List") .items.select("ID, Part, Level, ...

Navigating through unidentified object in Typescript

I'm working with an object that has an unknown format, specifically a users' CSV file. My task is to iterate through the keys to identify certain keys, such as phone numbers referenced as phoneNumbers1, phoneNumbers2, and so on in the .csv file. ...

Encountering an error when using Webpack ModuleFederationPlugin and HMR: "Undefined properties cannot be set"

Description Hey everyone! I've been experimenting with Webpack ModuleFederationPlugin using React and TypeScript in my current proof of concept. Currently, I have two applications - ChildApp which exposes a module, and a HostApp that consumes this e ...

Issue with Multer s3 upload: File not functioning properly in s3 and size increase of file

I successfully uploaded an mp4 file to s3 using node.js and the code seems to be functioning well as I can see the file in s3. However, there seems to be a discrepancy in the file size. The original file is 860kb but after uploading it, it increases to 1.4 ...

Angular is throwing an error that Localstorage is not defined

I'm currently working on a project and have encountered an issue with utilizing localStorage. My goal is to save the count state when the add button is clicked, so that even if I refresh the page, the number will remain intact. --- cart.service.ts--- ...