[英]Where to execute initialization functions in Angular /w Electron?
I am using Angular and Electron, and I have a Preferences
object I would like to initialize ( Preferences.init()
) which needs to be executed before any other code is executed .我正在使用 Angular 和 Electron,我有一个我想初始化的Preferences
对象( Preferences.init()
),它需要在执行任何其他代码之前执行。 Does Angular or Electron have a specific location where such initialization code should be executed? Angular 或 Electron 是否有执行此类初始化代码的特定位置?
At the moment I put it into the constructor of AppComponent
but since the function is asynchronous, I have a race condition and occasionally the data is not properly initialized when needed.目前我将它放入AppComponent
的构造函数中,但由于该函数是异步的,我有一个竞争条件,有时数据在需要时没有正确初始化。 Any help or suggestion is highly appreciated!任何帮助或建议都非常感谢! Thanks!谢谢!
You can use the APP_INITIALIZER
dependency injection token to do a such thing:你可以使用APP_INITIALIZER
依赖注入令牌来做这样的事情:
Assuming you created a provider假设您创建了一个提供程序
@Injectable()
export class ThingProvider {
private thing: Thing = null;
constructor(private http: Http) {
}
public getThing(): Thing {
return this.thing;
}
load() {
return new Promise((resolve, reject) => {
this.http
.get('https://my-api.com/thing')
.map(res => res.json())
.subscribe(response => {
this.thing = response['value'];
resolve(true);
})
})
}
}
Then, in your app.module.ts
file:然后,在您的app.module.ts
文件中:
export function thingsProviderFactory(provider: ThingProvider) {
return () => provider.load();
}
And finally, in the same file:最后,在同一个文件中:
@NgModule({
declarations: [
AppComponent
],
imports: [
BrowserModule,
HttpModule
],
providers: [
ThingProvider,
{ provide: APP_INITIALIZER, useFactory: thingsProviderFactory, deps: [ThingProvider], multi: true }
],
bootstrap: [AppComponent]
})
export class AppModule { }
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.