forRoot() 模块方法的参数如何传递给提供者? [英] how the parameters of a forRoot() module's method is passed to a provider?

查看:24
本文介绍了forRoot() 模块方法的参数如何传递给提供者?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我发现了一些模块的 forRoot() 方法示例,如下所示:

I found some examples of module's forRoot() method like the one below:

export class CoreModule {
constructor(
@Optional()
@SkipSelf()
parentModule: CoreModule
) {
if (parentModule) {
  throw new Error(
    'CoreModule is already loaded. Import it in the AppModule only'
  );
 }
}
static forRoot(someParameters?:string[]): ModuleWithProviders {
  return {
  ngModule: CoreModule,
  providers: [AnProvider1, AnProvider2]
 };
}

但是我怎样才能将参数值传递给任何模块声明的提供者?

But how can I to pass the parameter values to any of the module's declared providers ?

推荐答案

使用 InjectionToken 向注入器注册参数.然后使用 DI 传入 InjectionTokendeps 属性,如下所示:

Use InjectionToken to register the parameters with the injector. Then use DI passing in the InjectionToken with the deps property as follows:

export const Params= new InjectionToken<string[]>('params');

...

static forRoot(someParameters?:string[]): ModuleWithProviders {
  return {
  ngModule: CoreModule,
  providers: [
            { provide: Params, useValue: someParameters },
            { provide: AnProvider1, useClass: AnProvider1, deps:[Params] },
            AnProvider2
  ]
};

在您的组件构造函数中,使用 InjectionToken:

In your component constructor, use the InjectionToken:

constructor(@Inject(Params) someParameters: string[])

这篇关于forRoot() 模块方法的参数如何传递给提供者?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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