Creating a dynamic configuration for service instantiation in Angular 4/5

Currently working on a library that has an AuthModule with an AuthService for managing OAuth2 authentication using oidc-client-js. I want the application using this library to be able to set up the configuration for the OAuth client. One way to do this is by providing the configuration in the forRoot method of the AuthModule:

AuthModule.forRoot({
    applicationNamespace: 'ConsumingApp',
    clientId: 'consuming.app'
});

In the forRoot method, I would like to initialize the service with the provided config.

I found a workaround by setting the properties on the window object and then accessing them in the AuthService as window.clientId and window.applicationNamespace.

(window as any).applicationNamespace = authConfig.applicationNamespace;
(window as any).clientId = authConfig.clientId;

Is there a more efficient or proper way to achieve this?

Answer №1

To achieve this, you can utilize an injection token as outlined below.

First: Establish an InjectionToken to represent the configuration object that will be provided:

export const CONFIG_OPTIONS = new InjectionToken<ConfigOptions>('configOptions');

Second: Inject the token into the ConfigurationService constructor

Third: Make sure to pass the configuration object when calling the initialization function for your module

public static initialize(configOptions: ConfigOptions): ModuleWithProviders

Finally: Set the received configuration as the value for the injection token

{ provide: CONFIG_OPTIONS, useValue: configOptions }

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 Error 500 with Jquery Min.Map File

ERROR: GET request to http://domain.com/assets/js/jquery-1.10.2.min.map returned a 500 Internal Server Error Can anyone help me figure out what's causing this error? I checked the log files in /var/log/error but couldn't find any information. T ...

Issue with Angular 7: In a ReactiveForm, mat-select does not allow setting a default option without using ngModel

I have a Angular 7 app where I am implementing some reactive forms. The initialization of my reactive form looks like this: private initFormConfig() { return this.formBuilder.group({ modeTransfert: [''], modeChiffrement: [' ...

The failure of the ajax call to encapsulate is likely due to issues with object visibility

Having some trouble with a piece of code meant to run smoothly on Firefox 3.6. The issue arises when the variable this.xmlhttp, defined in STEP2 and used in STEP3, seems to be operating in different variable environments. Even though I expect the two usa ...

Unable to locate the JavaScript files within the NextJs and ReactJs project

I've encountered an issue when trying to import js files (which are libraries) in my project. I am currently using NextJS version 14.1.3 and ReactJS version 18.2.0. You can find the path to these files here Here is a glimpse of the project structure ...

rearrange results in ng-repeat based on specified array in AngularJS

Currently delving into Angularjs and have a quick query: I recently received an array from a user which looks like this: userPreferences = [7,5,4] Additionally, I am working with an object that uses ng-repeat to showcase various news items. The object s ...

Using Selenium to interact with a link's href attribute through JavaScript

New to Java and Selenium, I'm facing difficulties when trying to click on a link with JavaScript in href attribute. Here's the snippet from the page source: href="javascript:navigateToDiffTab('https://site_url/medications','Are y ...

Overriding a shared module service in Angular from a separate module: A step-by-step guide

I am working with various modules such as SchoolModule, UniversityModule, and SharedModule The SharedModule includes a BaseService that both the SchoolModule and UniversityModule providers are utilizing as an extension When loading the SchoolModule, I ne ...

"Can you share a method to extract the value from a TextField component in a React hook-based Material-

Currently, I am using Material-UI within a React project and have a component set up like this: const UserDetail = (props: ListDetailProps) => { const oldpassword = useRef<TextFieldProps>(null); const newpassword = useRef<TextFieldProps ...

Self-referencing type alias creates a circular reference

What causes the discrepancy between these two examples? type Foo = { x: Foo } and this: type Bar<A> = { x: A } type Foo = Bar<Foo> // ^^^ Type alias 'Foo' circularly references itself Aren't they supposed to have the same o ...

displaying 'undefined' upon completion of iterating through a JSON file using $.each

For my project, I am attempting to extract only the date data from a JSON object. I have successfully looped through the object and displayed it, but the issue arises at the end of the loop where it shows undefined. I am not sure what mistake I am making. ...

Verify and retrieve information from the Dynamics CRM Web API with the help of Angular 2 (TypeScript)

How can one authenticate and query the Dynamics CRM Web API from a Single Page Application developed with Angular 2 (TypeScript)? Initial research indicates that: The Dynamics CRM (version 2016 or 365) instance needs to be registered as an application ...

Problem with Vue.js dropdown functionality in Internet Explorer

After developing a form using Vue.js to allow users to save and return to their answers, I encountered an issue in Internet Explorer. When the page loads, the dropdown menu tied to a computed property does not display the previously selected answer as expe ...

Grab a hold of the currently active controller in Angular

Is it possible to access a reference to the current instance of the controller from within its definition? My goal is to use `$compile` to create a modal and have it bound to the same controller that initiated its creation. Below is an example of what I w ...

The dark theme in React Material UI will be specifically targeted and applied only to the drawer

I want to implement a dark theme specifically for the drawer component. In Drawer.js <ThemeProvider theme={theme}> <div> {props.token && ( <Drawer anchor="left" open={props.isDrawerOpen} ...

unable to implement multiple layouts while utilizing react-router

My current project requires two different layouts: one for the homepage (currently implemented in app.js) and another for the result page. After submitting a form, the results should be displayed in the result layout instead of the app layout. However, whe ...

Authenticating users in Laravel without requiring a password

I've been attempting to enable passwordless login in a Laravel application, but I keep encountering an error message that says: Argument 1 passed to Illuminate\Auth\SessionGuard::login() must be an instance of Illuminate\Contracts\ ...

Convert data in JavaScript and send it as a string in PHP

I'm currently facing a small issue with my JavaScript code. Specifically, I am using AJAX and attempting to retrieve a variable in PHP. Everything seems to be working fine except for the "param" data. Below is the snippet of my code: $('#sign ...

Troubleshooting: Issues with Jquery's has, find, contains functions

As I check whether an element contains another element, I've previously utilized the jquery element.has(secondElement) function. In my angularjs project, I make use of jquery within a directive where I transclude elements through markup using ng-tran ...

What is the process for installing fontawesome using npm?

I encountered an error while attempting to install that looks like the following: $ npm install --save @fortawesome/fontawesome-free npm WARN saveError ENOENT: no such file or directory, open 'C:\Users\Admin\Desktop\package.json&a ...

Encountered an error stating 'name' property is undefined while using @input in Angular 2

Everything seems to be set up correctly, but I'm encountering an error in the browser console that says "Cannot read property 'name' of undefined": This is how my media.component.ts file is structured: import { Component, Input } from &apo ...