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

时间:2016-09-12 14:15:09

标签: json angular config

我已升级到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);

1 个答案:

答案 0 :(得分:8)

我遇到了同样的问题。看起来你遇到了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);

它不是最漂亮的(它真的不是那么糟糕),但我从this post找到了一些我甚至不知道可能的东西。看起来你可以在函数中声明模块

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