9

There is an excellent article of how to bootstrap an angular1 application asynchronously. This enables us to fetch a json from the server before bootstrapping.

The main code is here:

(function() {
    var myApplication = angular.module("myApplication", []);

    fetchData().then(bootstrapApplication);

    function fetchData() {
        var initInjector = angular.injector(["ng"]);
        var $http = initInjector.get("$http");

        return $http.get("/path/to/data.json").then(function(response) {
            myApplication.constant("config", response.data);
        }, function(errorResponse) {
            // Handle error case
        });
    }

    function bootstrapApplication() {
        angular.element(document).ready(function() {
            angular.bootstrap(document, ["myApplication"]);
        });
    }
}());

How do I achieve the same with Angular 2?

Shaohao
  • 3,471
  • 7
  • 26
  • 45
David Michael Gang
  • 7,107
  • 8
  • 53
  • 98

3 Answers3

14

In fact, you need to create explicitly an injector outside the application itself to get an instance of Http to execute the request. Then the loaded config can be added in the providers when boostrapping the application.

Here is a sample:

import {bootstrap} from 'angular2/platform/browser';
import {provide, Injector} from 'angular2/core';
import {HTTP_PROVIDERS, Http} from 'angular2/http';
import {AppComponent} from './app.component';
import 'rxjs/Rx';

var injector = Injector.resolveAndCreate([HTTP_PROVIDERS]);
var http = injector.get(Http);

http.get('data.json').map(res => res.json())
  .subscribe(data => {
    bootstrap(AppComponent, [
      HTTP_PROVIDERS
      provide('config', { useValue: data })
    ]);
  });

Then you can have access to the configuration by dependency injection:

import {Component, Inject} from 'angular2/core';

@Component({
  selector: 'app',
  template: `
    <div>
      Test
    </div>
  `
})
export class AppComponent {
  constructor(@Inject('config') private config) {
    console.log(config);
  }
}

See this plunkr: https://plnkr.co/edit/kUG4Ee9dHx6TiJSa2WXK?p=preview.

Thierry Templier
  • 198,364
  • 44
  • 396
  • 360
  • 1
    First, thanks so much for this solution. Second, would a promise be better in this situation, since you would probably only be expecting one result and you want a response in either case (success or failure)? i.e. `http.get('data.json').toPromise()` Or does it really matter? – dspies Apr 22 '16 at 19:56
  • 1
    @dspies you're welcome! I understand your comment regarding promises but in the case of http only one event is fired and it completes after... So no need to transform to a promise ;-) – Thierry Templier Apr 23 '16 at 06:46
3

I was trying to solve a similar problem and I needed not only to bootstrap the application asynchronously, but also to use an asynchronously initialised service in my application. This is the solution, maybe it will be useful for someone:

let injector = ReflectiveInjector.resolveAndCreate([Service1,
{
    provide: Service2,
    useFactory: (s1: Service1) => new Service1(s2),
    deps: [Service1]
}]);

let s1: Service1 = injector.get(Service1);
let s2: Service2 = injector.get(Service2);

s2.initialize().then(() => {
bootstrap(Application, [
    ...dependencies,
    {
        provide: Service2,
        useValue: s2     // this ensures that the existing instance is used
    }
    // Service2 - this would create a new instance and the init would be lost
    ]);
}); 
Kuba Beránek
  • 458
  • 9
  • 19
0

The Thierry Templier method also works with jQuery. Here is my solution with angular 2.3.1 (file main.ts):

import './polyfills.ts';

import { platformBrowserDynamic } from '@angular/platform-browser-dynamic';
import { enableProdMode } from '@angular/core';
import { environment } from './environments/environment';
import { AppModule } from './app/app.module';
declare var $: any;

if (environment.production) {
  enableProdMode();
}

$.ajax({
    'url': './assets/config.json',
    'type': 'GET',
    'success': function(data) {
      platformBrowserDynamic(
        [
          {
            provide: 'appConfig',
            useValue: data
          }
        ]
      ).bootstrapModule(AppModule);
    }
});
Kantauver
  • 3
  • 3