Injection of environmental variables into app services

Through the use of Nx, I have created multiple apps that each have their own environment with different API URLs. The Nx Workspace library includes shared services that are utilized among all apps, however, it is necessary to pass the environment-api-url when injecting the service into a component.

    @Component({
      standalone: true,
      imports: [
       ReactiveFormsModule,
       FormsModule,
       HttpClientModule
      ],
      providers: [AuthenticationService],
      selector: 'app-login',
      templateUrl: './login.component.html',
      styleUrls: ['./login.component.css'],
    })
    export class LoginComponent implements OnInit {
     ngOnInit() {}
    }

Is it possible to pass parameters like this?

providers: [AuthenticationService<environment>]

Or is there another method to achieve this?

Any advanced suggestions are highly appreciated!

Answer №1

Start by creating a new library named app-config. Inside, create an index.ts file at

lib/app-config/src/lib/config/index.ts
.

In the index.ts file, export an InjectionToken as follows:

import { InjectionToken } from '@angular/core';

export const APP_CONFIG = new InjectionToken('App Configuration');

Add this to the Providers array in your LoginComponent:

import { APP_CONFIG } from '@YourWorkspaceName/app-config';

providers: [
    {
      provide: APP_CONFIG,
      useValue: environment,
    },
    AuthenticationService
]

Next, inject APP_CONFIG into your AuthenticationService to access environment variables:

import { APP_CONFIG } from '@YourWorkspaceName/app-config';

    export class AuthenticationService {
     private readonly url: string = this.appConfig.authServiceUrl;
    
     constructor(
        private http: HttpClient,
        @Inject(APP_CONFIG) private appConfig: any
      ) {}
    
     login(EmailAddress: string, Password: string): Observable<any> {
        return this.http.post<{ authToken: string }>(`${this.url}/login`, {
          EmailAddress,
          Password,
        });
      }
    }

Hopefully you find these instructions beneficial.

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

Fastify Typescript: dealing with an unidentified body

I'm new to Fastify and I've encountered a problem with accessing values in the body using Typescript. Does anyone have any ideas or suggestions? Thanks! Update: I want to simplify my code and avoid using app.get(...) Here's my code snippet ...

Issue with Angular Material: Default selection not being applied in mat-select component

When I have a mat-select with options defined as objects in an array, I am facing an issue where the default selected value is not being set when the page renders. In my TypeScript file, I have: public options2 = [ {"id": 1, "name": "a"}, {"id": 2 ...

Is Angular4 preloaded with bootstrap library?

I started a new angular4 project and wrote the code in app.component.html <div class="container"> <div class="row"> <div class="col-md-1">.col-md-1</div> <div class="col-md-1">.col-md-1</div> <div class ...

There is a complete absence of text appearing on the html page when Angular is

Currently, I am in the process of learning Angular during my internship. As part of the requirements, I have been tasked with developing a client-server application using Angular as the frontend framework and Spring as the backend solution. Within the proj ...

The text editor within the NG nickname terminal

After purchasing a new Windows computer, I encountered an issue while attempting to install Angular. The ng commands were not functioning as expected and instead opened a file in the editor. Upon researching a solution at this source, it was suggested tha ...

Issue with Material UI v5: "spacing" property not found on custom theme object

My current setup involves using version 5 of material ui, where I have customized a theme and applied it to all my components. However, when trying to add padding to a paper element in one of my components based on the theme, I encountered the following e ...

Struggling to map a JSON file in a NextJS project using Typescript

I'm a beginner in JS and I'm currently struggling to figure out how to display the data from a json file as HTML elements. Whenever I run my code on the development server, I encounter the error message: "props.books.map is not a function&q ...

What is the process for utilizing global packages when running `ng serve`?

After successfully using npm to download and install packages globally for my project, I encountered an error when running ng serve --port 34000: C:\app>ng serve --port 34000 Node packages may not be installed. Try installing with 'npm install ...

Is it possible to retrieve a constant value while developing a customized rule in typescript-eslint?

I am currently working on implementing a custom ESLint rule using @typescript-eslint/utils that will display a warning if the prop kind of Category does not match a specific Regex pattern: import { ESLintUtils, TSESTree } from '@typescript-eslint/util ...

Is it possible to generate a user profile using Firebase Cloud Functions and assign the user id as the document id?

I'm having trouble generating a user profile document in Firebase cloud functions using the user.uid as the doc id. Below is the script I am working with, but it keeps failing. I suspect there might be a syntax issue, so any suggestions would be great ...

Exploring in Angular 2 by using First Name, Last Name, and Email for queries

Details Currently, I am working on implementing a search functionality using pipes. Users should be able to search by email, first name, or last name. At the moment, it only works for searching by email. I am looking to extend this capability so that user ...

Steps for showing a component (popup modal) just one time with React hooks

Is there a way to implement a popup modal that only appears once using hooks and localStorage? The modal should already appear upon page load. const [showModal, setShowModal] = useState<boolean>(true) return( <ModalIsContractor ...

The Angular map function is throwing an error stating "undefined is not a function"

Currently, I'm diving into this fantastic tutorial on Angular 2 and VS Code. Following the steps, I set up a db.json server to experiment with an API using test data structured as follows: { "articles": [{ "id": 1, "name": "Wa ...

Error occurred during the Uglify process: Unable to access the 'kind' property as it is undefined

I developed a project using TypeScript (version 3.9.3) and Node (version 10.16.3), but now I want to minify the code by converting it to JavaScript and running UglifyJS. However, after going through this process, the services that were functioning properly ...

Troubleshoot: Issue with binding data from DynamicComponentLoader in Angular 2 template

My implementation involves the utilization of DynamicComponentLoader and is based on the Angular2 API Guide. https://angular.io/docs/ts/latest/api/core/DynamicComponentLoader-class.html The code structure I have set up looks like this: import {Page} fro ...

Three.js and Angular - the requested function cannot be found

In my latest project, I created a basic application using Angular 4 and three.js to display a cube. The main part of the code resides in an Angular component called ViewerComponent, where the cube is rendered. I've simplified the relevant part of the ...

Previewing images with Dropzone through extending file types

Want to display an image preview before uploading using dropzone. Attempting to access the images by calling file.preview but encountering the error "it does not exist on type File." Dropzone extends the file type with a preview?: string. How can I access ...

Retrieve data from Ionic storage

Need help with Ionic storage value retrieval. Why is GET2 executing before storage.get? My brain needs a tune-up, please assist. public storageGet(key: string){ var uid = 0; this.storage.get(key).then((val) => { console.log('GET1: ' + key + ...

Accelerated repository uses TypeScript to compile a node application with dependencies managed within a shared workspace

Struggling to set up an express api within a pnpm turborepo workspace. The api relies on @my/shared as a dependency, which is a local workspace package. I have been facing challenges in getting the build process right. It seems like I need to build the s ...

The variable is accessed before it is initialized in the context of Next.js and Server Actions

Currently, I am utilizing the new Data Fetching feature in Next JS to retrieve data from an API and store it in a variable named 'contact.' However, I am facing the issue of receiving an error message stating that "variable 'contact' is ...