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.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…