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

查看:50
本文介绍了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天全站免登陆