Add a service to populate the values in the environment.ts configuration file

My angular service is called clientAppSettings.service.ts. It retrieves configuration values from a json file on the backend named appsettings.json.

I need to inject this angular service in order to populate the values in the environment.ts file. Specifically, the instrumentationKey should be obtained from the service (clientAppSettings.service.ts). Any assistance would be greatly appreciated.

Below is the content of the environmen.ts file:

export const environment = {
  production: false,
  appInsights: {
    instrumentationKey: 'some-key'
  } 
};

The angular service code found in clientAppSettings.service.ts :

@Injectable()
export class ClientAppSettingService {
  appUrl: string = "";
  constructor(private http: HttpClient, @Inject('BASE_URL') baseUrl: string) {
    this.appUrl = baseUrl;
  }
  getConfig() {
    return this.http.get<ClientAppSettings>(this.appUrl + 'api/ClientAppSettings');
  }
}

The backend controller details are as follows:

namespace WebApp.Controllers
{
    [Route("api/[controller]")]
    public class ClientAppSettingsController : Controller
    {
        private readonly AppSettings _clientAppSettings;

        public ClientAppSettingsController(IOptions<AppSettings> appSettings)
        {
            _clientAppSettings = appSettings.Value;
        }

        [HttpGet("[action]")]
        public AppSettings Get()
        {
            return _clientAppSettings;
        }
    }
}

Lastly, here is the content of the appsetting.json:

{
"AppConfig": {
        "ApplicationInsights": {
            "InstrumentationKey": "some-key"
        }
}

Answer №1

Updating the environment file during runtime is not possible since Angular utilizes it during the build process. Instead, store the settings in your service and retrieve them from there.

Answer №2

It appears that the method you described may not be feasible as outlined here (https://github.com/angular/angular-cli/issues/2508). Environment files are typically utilized to define certain constants for a specific environment.

To store data retrieved from the backend within your application, consider implementing a shared service dedicated to managing and storing the data.

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

Leveraging React and TypeScript's capabilities to pass around arguments efficiently

As I integrate TypeScript into my application, I find myself at a juncture where I need to specify the following: { id, label, type, styles, ...props } Incorporating this structure into a component like the one below: const TestComponent = ({ id, label, t ...

Having trouble accessing child pages using the router

In my Angular 2 application, I have implemented navigation successfully with the following routes: { path: 'layer1/layer2', component: C2 } } { path: 'layer1/layer2/layer3', component: C3, canDeactivate: [CanDeactivateGuard] } }, With ...

Mismatched URLSearchParam type {property: value} does not match with undefined and Argument Type {property: value} cannot be assigned to {property: value}

Every time I try to run the code below, I encounter this error. The code is supposed to take a refresh token as input and make a POST request using URLSearchParams to a specific URL. However, I keep getting an error related to URLSearchParams. https://i.s ...

React.js with Typescript is throwing an error stating that a property does not exist on the child component

Currently, I am working with React in conjunction with typescript 2.3.4. I keep encountering the error TS2339: Property 'name' does not exist on type 'Readonly<{ children?: ReactNode; }> & Readonly<{}>'. This issue arises wh ...

Load information into a different entity

I need help with adding new values to an existing object. When I receive some form data from noteValue, I also have additional input data in my component under person that I would like to integrate into noteValue before saving it. let noteValue = form.va ...

Tips for customizing the appearance of Angular Material select drop down overlay

In my project, there is an angular component named currency-selector with its dedicated css file defining the styling as shown below: .currency-select { position: absolute; top: 5px; right: 80px; z-index: 1000000; color: #DD642A; f ...

Using TypeScript with AWS Lambda: To package imports or not to package? Alternatively: Error in Runtime.ImportModule: Module '@aws-sdk/...' not found

I have been working with the code in my lambda.ts file, attempting to execute it on an AWS Lambda: import 'aws-sdk' import { /* bunch of stuff... */ } from "@aws-sdk/client-cloudwatch-logs"; import {Context, APIGatewayProxyResult} from ...

Diverse behaviors exhibited by an array of promises

I've developed a function that generates an array of promises: async addDefect(payload) { this.newDefect.setNote(payload.note); this.newDefect.setPriority(payload.priority); const name = await this.storage.get(StorageKeys.NAME); ...

The functionality of expandable rows on the material table seems to be malfunctioning once sorting is

After implementing expandable rows and sorting in my table based on the samples provided in Angular Material Table, I encountered an issue. When I try to expand a row after sorting the table, the first click appears to have no effect. The second click brie ...

Attempting to utilize the setInterval function in Ionic 4 to invoke a specific function every second, unfortunately, the function fails to execute

Working with Ionic 4 has been a breeze for me. Recently, I encountered a situation where I needed to update the value of an ion-range every second by invoking a function. However, despite successfully compiling the code, the changeMark function never seeme ...

Angular 2 - Conceal Table Panel if there is no data in the table

I am using *ngFor to generate panels that contain tables. Each table uses *ngFor to create <td> elements for each item in a dataset. Sometimes the table will have empty rows. Is there a clever way to hide the panel when the table has no children? I ...

Error encountered in Storybook: The value is not iterable (property Symbol(Symbol.iterator) cannot be read)

I recently created a React library using and opted for the React + TypeScript + Storybook template. You can find the entire codebase here → https://github.com/deadcoder0904/react-typical I encountered the following error: undefined is not iterable ( ...

Is there a way to assign API data as inner HTML using Lit?

Need help setting inner html of html elements with a get request Any suggestions on how to achieve this? import { LitElement, html, css } from "lit"; import { customElement } from "lit/decorators.js"; import axios from "axios" ...

Issue encountered while trying to determine the Angular version due to errors in the development packages

My ng command is displaying the following version details: Angular CLI: 10.2.0 Node: 12.16.3 OS: win32 x64 Angular: <error> ... animations, cdk, common, compiler, compiler-cli, core, forms ... language-service, material, platform-browser ... platfor ...

Ways to detect button click in a separate component

I am working with an Angular app that consists of two components: a navbar component and a display component. The navbar component has a search button that, when clicked, searches for the entered name and displays the details in the display component. I ne ...

What is the best way to pass updates from input model class in a child component to its parent in Angular 13?

What is the best way to propagate changes in the input model class from a child component to its parent in Angular 13? Child Component export class ChildComponent implements OnInit { @Input() mdlInData: any; @Output() mdlOutData = new EventEmitter< ...

Tips for displaying only a single list item at a time using ngFor in Angular

Here is the situation: I have a code snippet that includes an icon within an anchor tag. Upon clicking the icon, a list with li tags is displayed. The issue arises when using ngFor. For example, if i=2, the li is created twice; for i=3, it is created thr ...

Utilize the useState hook to update state when changes occur in the

I currently have a functional component that utilizes a useState hook. The values it holds are sourced from my redux store, and I aim to update the state with the new store state every time an action is dispatched. At the moment, I've manually set an ...

Displaying all notifications while using parameters in TypeScript

I am trying to display all of my notifications in HTML. The value is returned in res = response.json();, but my website only shows one notification, similar to the example in https://i.sstatic.net/ECbyx.png Let's start with this code: public event ...

Executing ts-node scripts that leverage imported CSS modules

Is there a way to execute scripts that utilize css modules? I am currently working on a typescript migration script that I would like to execute using ts-node. The ideal scenario would be to keep the script's dependencies separate from the React comp ...