使用forRoot传递配置数据

Mic*_*oye 43 typescript angular2-services angular2-aot angular

我试图将配置数据传递到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 {}
Run Code Online (Sandbox Code Playgroud)

在我的自定义库中,特别是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]
    };
  }
}
Run Code Online (Sandbox Code Playgroud)

我的问题是如何在自定义库中提供配置数据 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);
  } 
}
Run Code Online (Sandbox Code Playgroud)

我已经阅读了关于提供商的文档,但是这个forRoot例子很小,似乎并不涵盖我的用例.

Gün*_*uer 71

你是几乎没有,只需同时提供SampleServiceconfig你的模块中象下面这样:

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

  foo: string;

  constructor(@Inject('config') private config:CustomConfig) {
    this.foo = ThirdParyAPI( config );
  }
}
Run Code Online (Sandbox Code Playgroud)

  • 很棒的答案!我通常使用它而不是`string`我更喜欢使用`OpaqueToken(InjectionToken)` (3认同)
  • 如果有嵌套模块怎么办,我该如何传递配置?我的意思是我不能在 AppModule 中使用: `imports: [ModuleA.forRoot(parentConfig)]` ,然后在 ModuleA 中使用 `imports: [ModuleB.forRoot(parentConfig.childConfig)]` 。 (3认同)
  • 谢谢 :)。我发现`OpaqueToken`太繁琐,无法解释,但是您当然是对的。这是首选方式。现在实际上是`InjectionToken` https://angular.io/docs/ts/latest/api/core/index/InjectionToken-class.html (2认同)
  • _Not_使用`InjectionToken`实际上说明了注射器的灵活性.它还演示了`@Inject(dep)`模式的用法,它非常有用. (2认同)