使用forRoot传递配置数据 [英] Pass config data using forRoot

查看:74
本文介绍了使用forRoot传递配置数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试将配置数据传递到Angular中的自定义库中.

I am trying to pass config data into a custom library in 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)中,我可以访问配置数据:


In my custom library, specifically the index.ts, I can access the config data:

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

My question is how do I make the config data available in the custom library's 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);
  } 
}

我已阅读提供商上的文档,但是forRoot示例非常少,似乎没有涵盖我的用例.

I have read through the docs on Providers, however the forRoot example is quite minimal and doesn't seem to cover my use case.

推荐答案

您快到了,只需在模块中同时提供SampleServiceconfig即可,如下所示:

You are almost there, simply provide both SampleService and config in your module like below:

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>

Since Angular 7 ModuleWithProviders is generic, so it needs ModuleWithProviders<SampleService>

这篇关于使用forRoot传递配置数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆