使用外部 json 配置文件的 Angular2 异步引导

Angular2 Ansychronous bootstrapping with external json configuration file

我已经升级到 angular2 RC6 并想在引导我的 AppModule 之前加载外部 JSON 配置文件。我在 RC5 之前有这个工作,但现在很难找到注入此数据的等效方法。

/** Create dummy XSRF Strategy for Http. */
const XRSF_MOCK = provide(XSRFStrategy, { provide: XSRFStrategy, useValue:  new FakeXSRFStrategyService() });

/** Create new DI. */
var injector = ReflectiveInjector.resolveAndCreate([ConfigService, HTTP_PROVIDERS, XRSF_MOCK]);

/** Get Http via DI. */
var http = injector.get(Http);

/** Http load config file before bootstrapping app. */
http.get('./config.json').map(res => res.json())
    .subscribe(data => {

        /** Load JSON response into ConfigService. */
        let jsonConfig: ConfigService = new ConfigService();
        jsonConfig.fromJson(data);

        /** Bootstrap AppCOmponent. */
        bootstrap(AppComponent, [..., provide(ConfigService, { useValue: jsonConfig })
    ])
    .catch(err => console.error(err));
});

这工作得很好,但很难改变以使用 RC6。

我正在尝试以下方法,但很难用加载的数据修改我预定义的 AppModule:

const platform = platformBrowserDynamic();

if (XMLHttpRequest) { // Mozilla, Safari, ...
  request = new XMLHttpRequest();
} else if (ActiveXObject) { // IE
  try {
    request = new ActiveXObject('Msxml2.XMLHTTP');
  } catch (e) {
    try {
      request = new ActiveXObject('Microsoft.XMLHTTP');
    } catch (e) {
      console.log(e);
    }
  }
}
request.onreadystatechange = function() {
  if (this.readyState === 4 && this.status === 200) {
    var json = JSON.parse(this.responseText);
    let jsonConfig: ConfigService = new ConfigService();
    jsonConfig.fromJson(json);
    /**** How do I pass jsConfig object into my AppModule here?? ****/
    platform.bootstrapModule(AppModule);
  }
};

// Open, send.
request.open('GET', './config.json', true);
request.send(null);

我遇到了同样的问题。看起来你遇到了 my Gist :-)

至于 RC 6 更新,您应该查看 HttpModule source。它显示了最初位于现已删除的 HTTP_PROVIDERS 中的所有提供程序。我刚刚检查了一下并提出以下内容

function getHttp(): Http {
  let providers = [
    {
      provide: Http, useFactory: (backend: XHRBackend, options: RequestOptions) => {
        return new Http(backend, options);
      },
      deps: [XHRBackend, RequestOptions]
    },
    BrowserXhr,
    { provide: RequestOptions, useClass: BaseRequestOptions },
    { provide: ResponseOptions, useClass: BaseResponseOptions },
    XHRBackend,
    { provide: XSRFStrategy, useValue: new NoopCookieXSRFStrategy() },
  ];
  return ReflectiveInjector.resolveAndCreate(providers).get(Http);
}

至于

/**** How do I pass jsConfig object into my AppModule here?? ****/
platform.bootstrapModule(AppModule);

它不是最漂亮的(它真的没那么糟糕),但我从 中发现了一些我什至不知道是可能的东西。看起来您可以在 内部 函数中声明模块。

function getAppModule(conf) {
  @NgModule({
    declarations: [ AppComponent ],
    imports:      [ BrowserModule ],
    bootstrap:    [ AppComponent ],
    providers:    [
      { provide: Configuration, useValue: conf }
    ]
  })
  class AppModule {
  }
  return AppModule;
}

下面是我刚刚用来测试的

import { ReflectiveInjector, Injectable, OpaqueToken, Injector } from '@angular/core';
import { platformBrowserDynamic } from '@angular/platform-browser-dynamic';
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { Observable } from 'rxjs/Observable';
import 'rxjs/add/operator/toPromise';
import {
  Http, CookieXSRFStrategy, XSRFStrategy, RequestOptions, BaseRequestOptions,
  ResponseOptions, BaseResponseOptions, XHRBackend, BrowserXhr, Response
} from '@angular/http';

import { AppComponent } from './app.component';
import { Configuration } from './configuration';

class NoopCookieXSRFStrategy extends CookieXSRFStrategy {
  configureRequest(request) {
    // noop
  }
}

function getHttp(): Http {
  let providers = [
    {
      provide: Http, useFactory: (backend: XHRBackend, options: RequestOptions) => {
        return new Http(backend, options);
      },
      deps: [XHRBackend, RequestOptions]
    },
    BrowserXhr,
    { provide: RequestOptions, useClass: BaseRequestOptions },
    { provide: ResponseOptions, useClass: BaseResponseOptions },
    XHRBackend,
    { provide: XSRFStrategy, useValue: new NoopCookieXSRFStrategy() },
  ];
  return ReflectiveInjector.resolveAndCreate(providers).get(Http);
}

function getAppModule(conf) {
  @NgModule({
    declarations: [ AppComponent ],
    imports:      [ BrowserModule ],
    bootstrap:    [ AppComponent ],
    providers:    [
      { provide: Configuration, useValue: conf }
    ]
  })
  class AppModule {
  }
  return AppModule;
}

getHttp().get('/app/config.json').toPromise()
  .then((res: Response) => {
    let conf = res.json();
    platformBrowserDynamic().bootstrapModule(getAppModule(conf));
  })
  .catch(error => { console.error(error) });