How to use HttpClient in Main.ts file

Viewed 819

The way my application is setup, there is a function in my main.ts that fetches a backendURL. That is then provided to the rest of the app (to be used as a base url for all other api calls) The problem is I am trying to setup a custom backend configuration that avoids a rebuild and requires the use of a provider which fetches the information of a JSON file. In my main.ts I am aware DI is unavailable and thus tried to create instances of each dependency manually but eventually hit a brick wall since HttpHandler is an abstract class.

The function in my main.ts currently looks something like this,

return new BackendService(new AppConfigService(new HttpClient(new HttpHandler()))).getCurrentBackend().backendUrl;

Is there another solution to this? Has anyone been able to successfully configure their angular project to reference environment variables to the main.ts file that would avoid a rebuild?

2 Answers

What you might be looking for is APP_INITIALIZER DI token.

In short you would create a provider class, encapsulate your call to backend in there and this class would receive HttpClient as DI (and whatever else you need). Then you provide this class to your app module and make sure you import every dependencies there.

Here's a nice little example or APP_INITIALIZER in action : https://devblog.dymel.pl/2017/10/17/angular-preload/

You can fetch API as follows:

fetch('config.json').then(res => res.json()).then((resp) =>{
   platformBrowserDynamic().bootstrapModule(AppModule);
})
Related