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

Service for language translation in Angular

I attempted to use an angular translation service to translate English words to Chinese using a key-value mapping approach, but unfortunately, I was unsuccessful. Does anyone have any suggestions? Here is the JSON mapping: "At most {{ number }} wrods ...

Unable to simulate a service and retrieve information in an angular unit test - showing as undefined

In my current project, I have a component that I am trying to write unit tests for. However, when I run the test, I noticed that the value of console.log('**fav**' + favorite[`isFavorite`]); shows up as undefined. This indicates that the data I ...

The issue is that only the first checkbox within ngFor is being toggled on and off each time a different checkbox is clicked

When I have checkboxes inside a ngFor loop and click on any one of them, only the first one gets checked and unchecked, updating only the status of the first checkbox. Here is the HTML template: <div *ngFor="let num of count" class="m-b-20"> & ...

Sending data from child components to parent components in Angular

I'm facing an issue with retrieving data from a child array named store within user data returned by an API. When trying to access this child array in my view, it keeps returning undefined. Code export class TokoPage implements OnInit { store= nu ...

Encountering an issue: "Failed HTTP response while trying to access https://localhost:44328/api/AllItProjectsLists/Index: 0 Error Message Unknown"

I am completely new to working with Angular. I have been working on a small application that is supposed to display a list of projects retrieved from a database on the Angular side. To achieve this, I am making a call from Angular to .NET Core 2.2. The dat ...

Comparison of valueChanges between ReactiveForms in the dom and component级主动形

Is there a method to determine if the change in valueChanges for a FormControl was initiated by the dom or the component itself? I have a scenario where I need to execute stuff() when the user modifies the value, but I want to avoid executing it if the v ...

Is the TypeScript compiler neglecting the tsconfig.json file?

I am new to TypeScript and currently exploring how to set it up in WebStorm. One of the first steps I took was creating a tsconfig.json file in the main directory of my project and updating the built-in TypeScript compiler to version 1.6.2. However, despit ...

What are the steps to integrate npm into a Cordova app within Visual Studio?

I am currently working on developing a hybrid app using the "Tools for Apache Cordova" project template in Visual Studio. To incorporate angular2 into my project, I have added all the necessary modules to packages.json. After compiling everything and reso ...

Why is the format incorrect when the Angular 7 (Change)-Function on Input of type Date isn't functioning?

I am facing an issue with updating the date using key input and assigning the selected date to a property of my object. Below is the code I'm currently working with: <input type="date" [value]="dateTime()" (change)="setDate($event)"/> The dat ...

Tips for bringing in a feature that is available in JavaScript but missing in TypeScript definitions and troubleshooting any resulting errors

Utilizing react-native-keyboard-aware-scroll-view, the library has the following exports in their code: export { listenToKeyboardEvents, KeyboardAwareFlatList, KeyboardAwareSectionList, KeyboardAwareScrollView } However, the index.d.ts file does n ...

Tips for successfully passing the dynamic state and setState to a function in typescript

I'm encountering an issue with passing dynamic state and setState into a function using Typescript. Despite trying to use Generics, I am facing complaints from Typescript. Here is the code snippet: const handleSelectTag = (tag: { color: string; labe ...

The art of representing objects and generating JSON responses

As I dive into building a web application using NextJS, a versatile framework for both API and user interface implementation, I find myself pondering the best practices for modeling and handling JSON responses. Key Points In my database, models are store ...

How to reference 'this' within a d3 callback when using Angular 7

In an Angular directive, I am trying to access a class-level variable inside a callback function. To achieve this, I used an arrow function but the 'this' keyword is still not pointing to the directive. this.itemRects.selectAll('rect') ...

Utilizing string literals as index signatures

I've created a code snippet called MyTest that maps over an object: type MyTest<T> = { [P in keyof T]: T[P]; }; type Result = MyTest<{hello: 'world', foo: 2}>; // ^? type Result = { hello: 'world', foo: 2 } ...

Resize the textarea to fit a maximum of five lines, and display a scrollbar if necessary

Explanation: I am facing an issue in Angular 2 regarding the chat screen. I need the chat screen to dynamically increase in size as I type, up to a maximum of 5 lines, and then show a scrollbar. How can I achieve this functionality? Problem: The current b ...

Data from graphql is not being received in Next.js

I decided to replicate reddit using Next.js and incorporating stepzen for graphql integration. I have successfully directed it to a specific page based on the slug, but unfortunately, I am facing an issue with retrieving the post information. import { use ...

Upgrade from AngularJS 1.x to the latest version of Angular, AngularJS 2.x

Currently in the process of mastering AngularJS 2 in order to transition my applications from Angular 1.x. The differences between the two versions are quite significant. Can you please share the advantages of upgrading from Angular 1 to Angular 2? I am ...

Starting a fresh Angular project yields a series of NPM warnings, notably one that mentions skipping an optional dependency with the message: "npm

Upon creating a new Angular project, I encounter warning messages from NPM: npm WARN optional SKIPPING OPTIONAL DEPENDENCY: <a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="68e01b0d1e0d061c7518d7">[email protecte ...

get a duplicate of an object

Is this the proper method for creating a duplicate of an object? class ObjectWrapper { private _obj; /*** * Copy object passed as argument to this._obj */ constructor (_obj: Object) { this._obj = _obj; } /** Return copy of this._ ...

Guide to locating a particular node within an array of nested objects by utilizing the object

Dealing with an array of nested objects, the goal is to compare values with a flat array and update the property matchFound. If the parent's matchFound is true, then all its children should inherit this value. treeData = [{ field: 'make&a ...