使用forRoot传递配置数据

迈克尔·道伊(Michael Doye):

我试图将配置数据传递到Angular中的自定义库中。

在用户应用程序中,他们将使用以下命令将一些配置数据传递到我的库中forRoot

// Import custom library
import { SampleModule, SampleService } from 'custom-library';
...

// User provides their config
const CustomConfig = {
  url: 'some_value',
  key: 'some_value',
  secret: 'some_value',
  API: 'some_value'
  version: 'some_value'
};

@NgModule({
  declarations: [...],
  imports: [
    // User config passed in here
    SampleModule.forRoot(CustomConfig),
    ...
  ],
  providers: [
    SampleService
  ]
})
export class AppModule {}

在我的自定义库(特别是)中index.ts,我可以访问配置数据:

import { NgModule, ModuleWithProviders } from '@angular/core';
import { SampleService } from './src/sample.service';
...

@NgModule({
  imports: [
    CommonModule
  ],
  declarations: [...],
  exports: [...]
})
export class SampleModule {
  static forRoot(config: CustomConfig): ModuleWithProviders {
    // User config get logged here
    console.log(config);
    return {
      ngModule: SampleModule,
      providers: [SampleService]
    };
  }
}

我的问题是如何在自定义库的 SampleService

当前SampleService包含以下内容:

@Injectable()
export class SampleService {

  foo: any;

  constructor() {
    this.foo = ThirdParyAPI(/* I need the config object here */);
  }

  Fetch(itemType:string): Promise<any> {
    return this.foo.get(itemType);
  } 
}

我已经阅读了Providers上的文档,但是该forRoot示例非常少,而且似乎没有涵盖我的用例。

GünterZöchbauer:

您快要准备好了,只需在SampleServiceconfig在模块中同时提供如下所示:

export class SampleModule {
  static forRoot(config: CustomConfig): ModuleWithProviders<SampleModule> {
    // User config get logged here
    console.log(config);
    return {
      ngModule: SampleModule,
      providers: [SampleService, {provide: 'config', useValue: config}]
    };
  }
}
@Injectable()
export class SampleService {

  foo: string;

  constructor(@Inject('config') private config:CustomConfig) {
    this.foo = ThirdParyAPI( config );
  }
}

更新

由于Angular 7 ModuleWithProviders是通用的,因此需要ModuleWithProviders<SampleService>

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章