小编典典

带有外部json配置文件的Angular2异步引导

json

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

阅读 254

收藏
2020-07-27

共1个答案

小编典典

我有同样的问题。好像您遇到了我的要点
:-)

至于RC6更新,您应该签出HttpModule源。它显示了最初已被删除的所有提供程序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) });
2020-07-27