update2
Plunker example
update AoT
为了与AoT合作,工厂关闭需要迁出
function loadContext(context: ContextService) {
return () => context.load();
}
@NgModule({
...
providers: [ ..., ContextService, { provide: APP_INITIALIZER, useFactory: loadContext, deps: [ContextService], multi: true } ],
另见https://github.com/angular/angular/issues/11262
update元人民币.6和2.0.0最终示例
function configServiceFactory (config: ConfigService) {
return () => config.load();
}
@NgModule({
declarations: [AppComponent],
imports: [BrowserModule,
routes,
FormsModule,
HttpModule],
providers: [AuthService,
Title,
appRoutingProviders,
ConfigService,
{ provide: APP_INITIALIZER,
useFactory: configServiceFactory
deps: [ConfigService],
multi: true }
],
bootstrap: [AppComponent]
})
export class AppModule { }
如果不需要等待初始化完成,也可以使用`class AppModule{}的构造函数:
class AppModule {
constructor(/*inject required dependencies */) {...}
}
hint (cyclic dependency)
例如,注入路由可能会导致循环依赖.
this.myDep = injector.get(MyDependency);
而不是直接注射MyDependency
,比如:
@Injectable()
export class ConfigService {
private router:Router;
constructor(/*private router:Router*/ injector:Injector) {
setTimeout(() => this.router = injector.get(Router));
}
}
update
在RC中也应该如此.5,而是将提供程序添加到根模块的providers: [...]
,而不是bootstrap(...)
(我自己还没有测试过).
update
这里解释了一种完全在Angular 内完成的有趣的方法,https://github.com/angular/angular/issues/9047#issuecomment-224075188
您可以使用APP_INITIALIZER
,当
例如,假设您有一个多租户解决方案
在bootstrap中:
{provide: APP_INITIALIZER, useFactory: (sites:SitesService) => () => sites.load(), deps:[SitesService, HTTP_PROVIDERS], multi: true}),
地点.服务ts:
@Injectable()
export class SitesService {
public current:Site;
constructor(private http:Http, private config:Config) { }
load():Promise<Site> {
var url:string;
var pos = location.hostname.lastIndexOf(this.config.rootDomain);
var url = (pos === -1)
? this.config.apiEndpoint + '/sites?host=' + location.hostname
: this.config.apiEndpoint + '/sites/' + location.hostname.substr(0, pos);
var promise = this.http.get(url).map(res => res.json()).toPromise();
promise.then(site => this.current = site);
return promise;
}
注意:config
只是一个自定义配置类.rootDomain
美元是
'.letterpress.com'
用于此示例,并允许执行以下操作
aptaincodeman.letterpress.com
.
任何组件和其他服务现在都可以注入Site
个
此方法似乎缩短了启动延迟,否则
很明显,如果你在等待大的角形束
加载,然后在 bootstrap 开始之前加载另一个http请求.
original个
您可以使用Angulars依赖项注入传递它:
var headers = ... // get the headers from the server
bootstrap(AppComponent, [{provide: 'headers', useValue: headers})]);
class SomeComponentOrService {
constructor(@Inject('headers') private headers) {}
}
或者直接提供
class MyRequestOptions extends BaseRequestOptions {
constructor (private headers) {
super();
}
}
var values = ... // get the headers from the server
var headers = new MyRequestOptions(values);
bootstrap(AppComponent, [{provide: BaseRequestOptions, useValue: headers})]);