Angular2- Retrieving configuration information during application launch

Implementing a method to load configuration data from an ASP.NET web API using HTTP at startup via APP_INITIALIZER. This approach was influenced by a discussion on Stack Overflow about loading configuration in Angular2 here and here.

Snippet from app.module.ts:

providers: [
            HttpClient,
            {
                provide: APP_INITIALIZER,
                useFactory: (appConfigSvc:AppConfigService) => () => {
                    appConfigSvc.load();
                },
                deps: [AppConfigService],
                multi: true
            }, AppConfigService

The appConfig.Service.ts code snippet:

@Injectable()
export class AppConfigService {
    private serviceApiUrl = "api/AppConfigApi/";
    public applicationConfig: Appconfigmodel.IAppConfigModel;


    constructor(private _http: Http) {     
    }

    getApiConfig(): Appconfigmodel.IAppConfigModel {

        return this.applicationConfig;
    }

    load() { this.getApplicationConfig(); }



    getApplicationConfig(): Observable<Appconfigmodel.IAppConfigModel> {

        let headers = new Headers({ 'Content-Type': 'application/json' });

        let options = new RequestOptions({
            headers: headers
        });

                //pulling config data from web.config of a ASP.Net Web API2

        return this._http.get(this.serviceApiUrl + 'GetApplicationConfig', options)
            .map((response: Response) => <Appconfigmodel.IAppConfigModel>response.json())
            .do(data => console.log('All: ' + JSON.stringify(data)))
            .catch(this.handleError);
    }

Usage in components:

export class FirstComponent {

constructor(private _appConfigService: AppConfigService) {

    }

    ngOnInit() {
      this.applicationConfig= this._appConfigService.getApiConfig();      // The config dat is getting as  undefined
    }

//button click
clickButton()
{
this.applicationConfig= this._appConfigService.getApiConfig();  // The  config data is populated here
}

}

Encountering difficulty in accessing the config data in ngOninit of components, but accessible in button click event handler or similar delayed methods.

Any assistance is appreciated. Thank you.

Answer №1

In order to access the constructor variable, it should be made public.

When working with Angular2, I highly recommend using the ng tools, particularly Angular-cli.

To get started with Angular-cli, simply run 'npm install angular-cli -g' and make sure to read the readme for these tools. Personally, I prefer not to use Microsoft technologies for front-end development, despite being a fan of their software for over 20 years.

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

Choose the default value of the select tag if hardcoded options are used with ngModel

When the value is set by using this.model.type = OPTION_NR1, Angular automatically sets the HTML attribute ng-reflect-model to 0. However, the desired value for this HTML attribute should be OPTION_NR1 in order to populate the drop-down with Option1 instea ...

Retrieving user input from one component to be used in another component in Angular

I'm currently working on a structure that involves a navbar component and a form component https://i.stack.imgur.com/nPRLO.png Initially, I have a navbar component where I load user data using an ID stored in the session. In the right side component ...

Maintaining scroll position in React Router v6

My website's homepage displays a user's feed. When a user clicks on one of the feed cards, they are taken to a different URL. However, when the user returns to the homepage, it automatically scrolls to the top. I am looking for a way to preserve ...

Show all span elements in a map except for the last one

Within my ReactJS application, I have implemented a mapping function to iterate through an Object. In between each element generated from the mapping process, I am including a span containing a simple care symbol. The following code snippet demonstrates t ...

Angular HTTP Requests with Observables

In order to enhance the security of my Angular web application, I am currently in the process of developing a TypeScript method that will validate a JWT token on the server using an HTTP call. It is imperative for me that this method returns a boolean val ...

Receiving an error while passing properties to a React component: "Property 'firstName' is not found on type 'Readonly<{}>'."

As a beginner in React, I need some patience I'm attempting to create a simple component where users can input their first and last names, update the values, and see them displayed after clicking a button. However, I keep encountering TypeScript comp ...

The Fuel-ui module in Angular 2 fails to function properly when loaded from a different directory

We recently switched from ng-cli to Gulp for building our Angular2 project, and we are utilizing Fuel-ui. An unusual error has come up. We have incorporated Fuel-ui's alert component into one of our components. When referencing fuel-ui from node_mo ...

Rotating images on a canvas

We're currently implementing Ionic and Angular in our project. One issue we are facing is regarding image rotation on canvas. When we click on an image, the rotation works perfectly if it's a jpg file. However, when we pass a base64 image, the r ...

Trigger a function upon a user's departure from a page or route in Angular 2

Is there a way to trigger a function only when the current route changes away from a specific component, such as when navigating away from "..../user/user-details"? I want this method to execute regardless of whether the route is changed through user inter ...

Found in the NgModule.imports section of the AppModule, yet was unable to be identified as an NgModule class in Angular version 12.2.9

Just set up a fresh angular 12 application and installed version 12 of @angular/material. Now I'm trying to implement it by adding this basic element: <mat-drawer-container></mat-drawer-container> However, all I see in the browser is a wh ...

Unable to retrieve jwt tokens transmitted from the frontend to the backend

Having just started learning Django and simplejwt, I'm facing an issue with retrieving tokens sent from our Angular frontend labeled as "app_token" and "access_token". Despite trying variations like "HTTP_APP_TOKEN" and "HTTP_ACCESS_TOKEN", as well as ...

Discovering the existence of a child route in Angular

My goal is to implement a redirect for the User if they navigate to the wrong child route. I've set up a guard for a child component that requests data from an API, but I'm unsure how to handle the case where the data does not exist. I want to ei ...

Observable emitting individual characters instead of the entire string in an optional parameter of an activated route

Within an Angular component, I have a method with the following content: this.route.paramMap.pipe( switchMap((params: ParamMap) => { let fooValue = params.get('selectedid'); console.log("inside switch map with value as " + ...

What is the command to determine the version of TypeScript being used in the command line interface (CLI)?

I recently added TypeScript 1.7.4 using Visual Studio 2015, and it appears correctly installed within the IDE. However, when I check the version using tsc --version in the command line, it shows a different, older version - 1.0.3.0 instead of 1.7.4. Is t ...

TypeScript's type inference feature functions well in scenario one but encounters an error in a different situation

I recently tried out TypeScript's type inference feature, where we don't specify variable types like number, string, or boolean and let TypeScript figure it out during initialization or assignment. However, I encountered some confusion in its be ...

I'm curious if there is an eslint rule specifically designed to identify and flag any unnecessary spaces between a block comment and the function or

Can anyone help me find a solution to prevent the following issue: /** * This is a comment */ function foo() { ... } I need it to be corrected and formatted like this: /** * This is a comment */ function foo() { ... } ...

Preventing Redundancy in Angular 2: Tips for Avoiding Duplicate Methods

Is there a way I can streamline my if/else statement to avoid code repetition in my header component? Take a look at the example below: export class HeaderMainComponent { logoAlt = 'We Craft beautiful websites'; // Logo alt and title texts @Vie ...

Issue with IntelliJ: TypeScript Reference Paths Are Not Relative

I am currently using IntelliJ as my IDE, but I am facing an issue with configuring gulp-typescript to compile my typescript code. The problem arises from the fact that IntelliJ does not treat my reference paths relatively, instead it references them from m ...

Ionic threw an ERROR stating: TypeError - _co.toBoarding is not a function

While using Ionic 3/4, I encountered an error when trying to navigate between two components. This error has baffled me because everything was working fine with Ionic just three months ago. I am utilizing lazyload for component navigation. The specific er ...

Encountering a Cross-Origin Resource Sharing issue involving the Access-Control-Allow-Origin * setting in NodeJS and Angular

I'm currently working on a web application using Angular, and I encountered a CORS error when trying to connect the backend with the front end: Access to XMLHttpRequest at 'http://localhost:3700/api/save-project' from origin 'http://lo ...