加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > 安全 > 正文

angular – 使用forRoot传递配置数据

发布时间:2020-12-17 08:04:52 所属栏目:安全 来源:网络整理
导读:我试图将配置数据传递到Angular中的自定义库。 在用户应用程序中,他们将使用forRoot将一些配置数据传递给我的库 // Import custom libraryimport { SampleModule,SampleService } from 'custom-library';...// User provides their configconst CustomConfi
我试图将配置数据传递到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示例非常小,似乎并不涵盖我的用例。

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}]
    };
  }
}
@Injectable()
export class SampleService {

  foo: string;

  constructor(@Inject('config') private config:CustomConfig) {

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读