Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
668 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 Reply

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

56.8k users

...