我想知道在没有任何手动服务注入(inject)和运行的情况下导入模块时如何从模块运行服务,就像 RouterModule
做。
@NgModule({
imports: [
BroserModule,
MyModuleWithServicesThatShouldAutoRun,
]
})
export class AppModule { }
最佳答案
Disclaimer: this is based on another answer in which was not accepted as the right answer because there was a simpler and easier way to do what the OP needed.
您可以使用
APP_INITIALIZER
在任何其他应用程序代码运行之前运行初始化代码的注入(inject) token 。 APP_INITIALIZER
在 @angular/core
中定义你像这样包括它:import { APP_INITIALIZER } from '@angular/core';
APP_INITIALIZER
是 OpaqueToken
引用multi provider
ApplicationInitStatus
服务。它支持多个依赖项,您可以在提供程序列表中多次使用它,例如:@NgModule({
providers: [
MyService,
{
provide: APP_INITIALIZER,
useFactory: (service: MyService) => function() { return service.init(); },
deps: [MyService],
multi: true
}]
})
export class AppModule { }
这个提供者声明告诉
ApplicationInitStatus
运行 MyService.init()
的类方法。 init()
返回 Promise
和 ApplicationInitStatus
阻止应用程序启动,直到 Promise
解决。export class MyService {
// omitted other methods for brevity
init(): Promise<any> {
// start some observers, do the stuff you need
// you can even request something via http
return this.httpClient
.get('https://someurl.com/example')
.toPromise()
}
}
这样,init 中的任何内容都会运行并阻止应用程序加载,直到
Promise
解决。请注意,无论
init()
有多长,这都会增加您应用程序的前期加载时间。方法采取。要在打开路线之前加载内容,您应该使用 resolver反而。来源:
关于angular - 在Angular中导入模块时如何从模块自动运行服务?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57361724/