David Michael Gang David Michael Gang - 4 months ago 105
AngularJS Question

How to bootstrap an Angular 2 application asynchronously

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?

Answer

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.

Comments