Incorporate values from an external JSON file when declaring NgModule

At the moment, I have been implementing a common approach to load data from a JSON file into my Angular 5 application. This allows me to easily inject this content into my components. The process I am following is well documented in the Runtime configuration section.

To achieve this, I'm utilizing an npm package that requires initialization in my app.module.ts file.

@NgModule({
    declarations: [
        AppComponent
    ],
    imports: [
        /* .... */
        [MsalModule.forRoot({
            clientID: "...",
            authority: "...",
            redirectUri: <I need the value here from the JSON file>
        })]
    ],
    providers: [
        ConfigService,
        {
            provide: APP_INITIALIZER,
            useFactory: (config: ConfigService) => () => config.load(),
            deps: [ConfigService],
            multi: true
        }
    ]
    bootstrap: [AppComponent]
})
export class AppModule { }

Although I am aware that Angular-CLI supports different environment files, the dynamic nature of the JSON file makes it essential for me to fetch its values post-build rather than relying on pre-defined configurations.

Is there a feasible way to access a value from the JSON file directly within the NgModule declaration where it's needed?

Answer №1

If you're looking for a great solution, check out this alternative method provided in this StackOverflow thread

This approach allows the JSON file to be loaded as a JavaScript object, giving us access to it before declaring the NgModule.

Answer №2

We have the ability to load this JSON file and access its content even without having to declare the NgModule first.

Here is the JSON File:

{
    "apiUrl":"http://localhost:52361/"
}

And here is how it is used in the Module File:

import Configuration from '../assets/config.json'; 

GridModule.forRoot(Configuration.apiUrl)

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 impact does the size of the unpacked files have on the overall minified size of an npm package?

I've been working on shrinking the size of an npm package I created, and I've successfully reduced the unpacked size to around 210kb. https://www.npmjs.com/package/@agile-ts/core/v/0.0.12 <- 210kb https://www.npmjs.com/package/@agile-ts/core ...

Retrieve both the name and id as values in an angular select dropdown

<select (change)="select($event.target.value)" [ngModel]="gen" class="border border-gray-200 bg-white h-10 pl-6 pr-40 rounded-lg text-sm focus:outline-none appearance-none block cursor-pointer" id="gend ...

Adding a component dynamically with a link click in Angular: A step-by-step guide

I am encountering an issue with my web application setup. I have a navigation bar, a home page with left and right divs, and a view-associates component. My goal is to dynamically add the view-associates component into the home's right div when a spec ...

Press on a list item within Angular Material 2/4

My goal is to trigger a function when clicking on any row of a list or table. I have not been able to achieve this, so now I am attempting to have the function called when clicking on the first column of each row. The structure of my component.html, which ...

Steps for constructing an object literal with a property designated as the `keyof` type

Struggling to articulate my question, here is a simplified code snippet outlining what I aim to accomplish. class Example<T, TId extends keyof T> { public create(id: T[TId]): T { return { [TId]: id, // Encounter an error at this point. Ob ...

Transitioning from Angular 11 to 12 results in a clash of peer dependencies

Currently in the process of upgrading from Angular 11.2.14 to Angular 12.0.5, an issue has arisen: npm ERR! Could not resolve dependency: npm ERR! dev @angular-devkit/build-angular@"12.0.5" from the root project npm ERR! npm ERR! Conflicting peer ...

Velocity: The initial parameter was not recognized as a property mapping

I've been experimenting with Velocity for animations (without jQuery), but I'm running into an issue where I keep getting this error message: Velocity: First argument ([object HTMLDivElement]) was not a property map, a known action, or a regis ...

I don't understand why I'm receiving the error message "Unsafe assignment of an `any` value" when I clearly defined the value as a string with a default value

I am puzzled by the 2 eslint errors in this code snippet. The property is declared as a string with a default value: export default { name: '...', props: { x: { type: String, required: true, default: '' } ...

conditional operator that compares values in router events

As I examine an object, links = { link1: 'page1', link2: 'page2', link3: 'page3', link4: 'page4', link5: 'page5', link6: 'page6' } I possess a function for retrieving t ...

Assign a variable with the value returned by a function

Can you help me with this question I have about validating fields with a function using AbstractControl? errorVar: boolean = false function(c: AbstractControl): {[key: string]: string } | null { // validation if 'test' is true or not goes here ...

Angular 2 component downgrade issue: What causes the error when constructor parameters are involved? (SystemJS) Unable to resolve all parameters for (?)

Consider this line as an example: constructor(private elementRef: ElementRef, private zone: NgZone) {} In order for the downgrade to be successful without any errors, I must remove the parameters from the constructor. Otherwise, I encounter the follo ...

Adjust CSS style height dynamically

I am currently creating a leaderboard for users: <div class="user"> <ul id="jogadores" *ngFor="let u of sortedUsers$; let i=index;" (click)="routeToUser(u.id)"> <li class="user"> <img class="gravatar" src="https://www.gra ...

Update the Material V4 Style ts file to the latest version, Material V5

I am currently in the process of upgrading from material v4 to v5. The problem I am encountering is related to a styles.ts file that I used to import into my component. Initially, the beginning of the class looked like this: import { defaultFont, prima ...

Purge the inversify-js container and fetch fresh service instances

My frontend application in react-native utilizes inversify-js for service classes. I have implemented an IOC structure where services are shared as singleton instances, each with an init/destroy method to manage internal state. While the init/destroy mec ...

Using Webpack 4 and React Router, when trying to navigate to a sub path,

I'm currently working on setting up a router for my page, but I've encountered a problem. import * as React from 'react'; import {Route, Router, Switch, Redirect} from 'react-router-dom'; import { createBrowserHistory } from ...

What causes TypeScript to interpret an API call as a module and impact CSS? Encountering a Next.js compilation error

My website development process hit a roadblock when I tried integrating Material Tailwind into my project alongside Next.js, Typescript, and Tailwind CSS. The compilation error that popped up seemed unrelated to the changes, leaving me baffled as to what c ...

Updating the mat-icon in a row when a button is clicked

I am currently working on implementing the mat-table in my project. I am facing an issue where I need to change the mat-icon of a button based on a click event, but I only want this change to apply to a single row in the table. At the moment, I am able to ...

Occasionally, the translate.get function may return the key instead of the intended

I recently encountered an issue while working on a web application built with Angular 12 and ASP.NET Core 5. The application utilizes ngx-translate for internationalization, but I faced a problem with translating content in a new component that I added to ...

Show information stored in Angularjs2 file (.ts) within an HTML document

Here is the code snippet from my .ts file: constructor( private config : ConfigService, private http: Http){ this.getWS('ngoName') .do((data) => { console.log(data); this.saveObj(data); }).to ...

Reviewing for the presence of "Undefined" in the conditional statement within Transpiled Javascript code for

While perusing through some transpiled Angular code, I came across this snippet: var __decorate = (undefined && undefined.__decorate) || function (decorators, target, key, desc) { I'm puzzled by the usage of undefined in this context. Can an ...