compuguru
compuguru

Reputation: 1065

Loading a "configuration" in Angular2

I'm converting an existing app into Angular 2, and the client-side code gets its config from an API on the server (things like telemetry setup and URLs to other APIs). I have some services that depend on the URLs returned by that API to build the requests for data. How do I get the URLs into that service?

My initial plan was to make a new "configuration" service that will handle getting the data. But then (I believe) whenever you wanted to access a configuration property, you would have to "subscribe" to it to get the values out (at least, that's what I'm doing with the other services). I'd also have to figure out how to chain the responses, so once the data from the configuration service is returned, the data from the actual service requested fires.

To get around, I could call the configuration service in the App's constructor (so it would load the data the application's startup) and dump the data into a singleton. But then I'd need to make sure that things depend on the configuration data don't access the properties before their loaded.

Any suggestions for an approach I should take?

Upvotes: 3

Views: 448

Answers (1)

Ken Smith
Ken Smith

Reputation: 20445

I've taken several different approaches.

Probably the simplest is to inject the configuration values into the page server-side, so that you can start off knowing them, without having to worry about calling external API's.

If that won't work for you, then you can dump the properties into a singleton as you suggest. But you'd need to put a global Promise into that singleton (like the ready field below), which you would resolve as soon as you had the values retrieved. And then before using any of those values, chain your call off of that global config, e.g., something like this:

config.ready.done(function() { 
    // Use config properties
});

Upvotes: 1

Related Questions