Search code examples
angularwebpackbootstrappingangular-module

Bootstrapping an Angular 2 application with remote data


I'm attempting to setup an application where my Angular client app communicates with an API server. In this API server I have various environment variables declared to match it's different environments (currently development and production).

The Angular client should HTTP-get a portion of these env variables that are being served on an API endpoint http://myserver.com/api/client-config. I understand this should occur before the application is bootstrapped, but I don't understand where or how I should include the HTTP call.

app.module.ts

...
import firebaseConfig from './config/firebase.config'; 

@NgModule({
    declarations: [
        AppComponent,
        VrtVideoPlayer,
        VrtAppsComponent,
        SubtitlesComponent,
        RangeSliderComponent,
        listPipe
    ],
    imports: [
        BrowserModule, 
        FormsModule,
        NgbModule,
        VgCore, 
        VgControlsModule, 
        VgOverlayPlayModule, 
        VgBufferingModule,
        HttpModule,
        AngularFireModule.initializeApp( firebaseConfig() ),
        RouterModule.forRoot([
            { path: 'subtitles', component: SubtitlesComponent },
            { path: '', component: SubtitlesComponent },
        ]),
    ],
    providers: [ExtBrowserXhr],
    bootstrap: [AppComponent],
})
export class AppModule {}

app.component.ts

import {Component} from '@angular/core';

import '../node_modules/bootstrap/scss/bootstrap.scss';
import './common/styles/styles.scss';

@Component({
    selector: 'my-app',
    templateUrl: 'app.component.html',
})
export class AppComponent {
}

bootstrap.ts

import {platformBrowserDynamic} from '@angular/platform-browser-dynamic';
import {AppModule} from './app.module';

platformBrowserDynamic().bootstrapModule(AppModule);

More specifically The following import:

import firebaseConfig from './config/firebase.config'

relies on environment variables declared in the API server environment. Can I simply make my HTTP GET-request here? This wouldn't be an ideal solution if my application requires the config object served by http://myserver.com/api/client-config elsewhere. Is it possible to bootstrap my application with this data, and if so - What's best practice regarding this?


Solution

  • Just to answer my own question; In this particular case I decided that utilising a client-side implementation of environment variables was a proper way to address my problem, as opposed to attempting to import the ones defined on the server environment.

    I run my client using Webpack. A perfect example of a possible way to implement client-side environment variables can be found here:

    angular2-webpack-starter/wiki