更新AoT
要使用AoT,必须将factory关闭处移出
function loadContext(context: ContextService) { return () => context.load();}@NgModule({ ... providers: [ ..., ContextService, { provide: APP_INITIALIZER, useFactory: loadContext, deps: [ContextService], multi: true } ],更新 RC.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 { }如果不需要等待初始化完成,也可以使用类AppModule {}的构造函数:
class AppModule { constructor() {...} }提示(循环依赖)
例如,注入路由器可能会导致循环依赖性。要变通,请注入
Injector并获取依赖项
this.myDep = injector.get(MyDependency);
而不是
MyDependency像这样直接注入:
@Injectable()export class ConfigService { private router:Router; constructor( injector:Injector) { setTimeout(() => this.router = injector.get(Router)); }}更新
这应该在RC.5中相同,但是将提供程序添加到
providers: [...]根模块而不是
bootstrap(...)
(尚未测试自己)。
更新
解释了一种完全在Angular内部完成的有趣方法
您可以使用
APP_INITIALIZER,它将在应用程序初始化时执行功能,并在功能返回promise时延迟提供的功能。这意味着该应用程序可以在没有太多延迟的情况下进行初始化,并且您还可以使用现有的服务和框架功能。例如,假设您有一个多租户解决方案,其中站点信息依赖于从其提供服务的域名。这可以是[name]
.letterpress.com或与完整主机名匹配的自定义域。通过使用,我们可以掩盖一个事实,即这背后的承诺APP_INITIALIZER。在引导程序中:
{provide: APP_INITIALIZER, useFactory: (sites:SitesService) => () =>sites.load(), deps:[SitesService, HTTP_PROVIDERS], multi: true}),
sites.service.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'用于此示例,并允许类似的操作aptainpreman.letterpress.com。现在可以
Site将任何组件和其他服务注入其中并使用该.current属性,该属性将是一个具体填充的对象,而无需等待应用程序中的任何承诺。这种方法似乎减少了启动等待时间,否则,如果您等待大型Angular捆绑包加载,然后等待另一个HTTP请求,然后再启动引导程序,则启动延迟会非常明显。
原版的
您可以使用Angulars依赖项注入传递它:
var headers = ... // get the headers from the serverbootstrap(AppComponent, [{provide: 'headers', usevalue: headers})]);class SomeComponentOrService { constructor(@Inject('headers') private headers) {}}或
baseRequestOptions直接提供像
class MyRequestOptions extends baseRequestOptions { constructor (private headers) { super(); }}var values = ... // get the headers from the servervar headers = new MyRequestOptions(values);bootstrap(AppComponent, [{provide: baseRequestOptions, usevalue: headers})]);


