简体   繁体   English

在 app.module.ts 中调用 service 方法提供其他服务

[英]Call service method to provide other services within app.module.ts

I have a configuration service that provides a method called getConfiguration(): Observable <Configuration> .我有一个配置服务,它提供了一个名为getConfiguration(): Observable <Configuration>的方法。

In order to fill my external library, I would like to provide this method within app.module.ts (I want to fill the InjectionToken, which is expected in the library).为了填充我的外部库,我想在app.module.ts中提供此方法(我想填充库中预期的 InjectionToken)。

Now I wonder how I can/should call this logic in the providers block.现在我想知道如何/应该在提供程序块中调用此逻辑。

@NgModule({
  declarations: [AppComponent],
  imports: [
      //...
  ],
  providers: [
    {
        provide: MY_CONFIG,
        useValue: ConfigurationService.getConfiguration(), // <--- won't work!
    }
  ]
  bootstrap: [AppComponent],
})
export class AppModule {}

Can you help me with that?你能帮我解决这个问题吗?

If your library expects the token to be Observable <Configuration> , then you can use factory to provide the Observable value as follows:如果您的库希望令牌是Observable <Configuration> ,那么您可以使用工厂提供 Observable 值,如下所示:

More details on using factory provider: https://angular.io/guide/dependency-injection-providers#using-factory-providers有关使用工厂提供程序的更多详细信息: https://angular.io/guide/dependency-injection-providers#using-factory-providers


    function configFactory(configService: ConfigurationService) {
        return configService.getConfiguration();
    }

    ...
    providers: [
        {
            provide: MY_CONFIG,
            useFactory: configFactory,
            deps: [ConfigurationService]
        }
    ]
    ...


声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM