如何异步引导Angular 2应用程序

时间:2016-03-23 13:51:31

标签: angularjs angular

有一个excellent article如何异步引导angular1应用程序。这使我们能够在引导之前从服务器获取json。

主要代码在这里:

(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"]);
        });
    }
}());

如何使用Angular 2实现相同的目标?

3 个答案:

答案 0 :(得分:14)

实际上,您需要在应用程序本身之外显式创建一个注入器,以获取Http的实例来执行请求。然后,当提升应用程序时,可以在提供程序中添加加载的配置。

以下是一个示例:

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 })
    ]);
  });

然后您可以通过依赖注入访问配置:

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

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

请参阅此plunkr:https://plnkr.co/edit/kUG4Ee9dHx6TiJSa2WXK?p=preview

答案 1 :(得分:3)

我试图解决类似的问题,我不仅需要异步引导应用程序,还需要在我的应用程序中使用异步初始化服务。 这是解决方案,也许对某人有用:

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
    ]);
}); 

答案 2 :(得分:0)

Thierry Templier方法也适用于jQuery。 这是我的角度为2.3.1(文件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);
    }
});
相关问题