angular - 在Angular中导入模块时如何从模块自动运行服务?

标签 angular typescript

我想知道在没有任何手动服务注入(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反而。

来源:
  • https://stackoverflow.com/a/44731279/4367683 (这个答案基于)
  • http://www.learn-angular.fr/how-to-call-an-asynchronous-service-before-bootstrap/
  • 关于angular - 在Angular中导入模块时如何从模块自动运行服务?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57361724/

    相关文章:

    javascript - 将修改后的数组发布到 Observable

    用 !important 标志定义的 CSS 变量在 Angular 生产模式下消失

    Angular 2.0 - 注入(inject)的 Http 服务未定义

    angular - 如何通过 Angular 4 中的共享模块正确导入 Angular Material 模块?

    angular2 找不到名称要求

    javascript - 用于组件目的的 Angular 扩展 API 模型

    javascript - 在 Angular2 中使用 guard 捕获重定向路由

    javascript - 如何使用jscodeshift在节点添加 'await'?

    typescript :允许跨多个文件重复变量吗?

    Angular 2 组件与对象的双向数据绑定(bind)