Tomas Marik
Tomas Marik

Reputation: 4093

Angular 2: External configuration befor bootstrap - passing the value to AppModule

I am would like to configure my Angular 2 App from external json file.

In my main.ts I load the config.json

getHttp().get('/config.json')
         .map(response => response.json();)
         .subscribe(
           data => {
             let clientConf: ClientConfig = data;

             // here I want to pass clientConf to AppModule
             platformBrowserDynamic().bootstrapModule(AppModule);

          });

I wonder how to pass clientConf to AppModule to use in app.module.ts:

@NgModule({
     ...
    providers: [
          { provide: Configuration, useValue: clientConf }
           ...

Upvotes: 3

Views: 2399

Answers (3)

Henrik
Henrik

Reputation: 1937

I had trouble to follow the accepted answer by @tomas-marik which I think was otherwise good. Below is my adaptations in main.ts for use in Angular 8:

fetch('/assets/config.json').then(async res => {
  var clientConf = <ClientConfig>await res.json();

  platformBrowserDynamic(
    [{ provide: ClientConfig, useValue: clientConf }]
  ).bootstrapModule(AppModule)
    .catch(err => console.error(err));
});

Upvotes: 1

Tomas Marik
Tomas Marik

Reputation: 4093

Here is my solution:

....
.subscribe(
       data => {
         let clientConf: ClientConfig = data;

         // here I want to pass clientConf to AppModule
          platformBrowserDynamic(
                [{ provide: ClientConfig, useValue: clientConf }]
                ).bootstrapModule(AppModule);

      });

I didn't pass clientConf to AppModule, I set ClientConfig as extraProvider for platformBrowserDynamic instead.

Then if you want to use ClientConfig, just inject it:

@Component({
   selector: 'app-root',
   templateUrl: './app.component.html',
   styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit {

   constructor(private clientConfig: ClientConfig) { }
   .....

Upvotes: 8

Alex Jones
Alex Jones

Reputation: 370

If you are wanting to get data before the UI is loaded, you could try using route guards. They will allow you to prevent the user navigating to a route in your application until a condition is true.

You can return an observable from a route guard, allowing for async guarding.

Further reading about Angular route guards.

EDIT: using the resolve property of a route gaurd would be best fit for waiting on data.

Upvotes: -1

Related Questions