Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
691 views
in Technique[技术] by (71.8m points)

angularjs - 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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...