首页 > 解决方案 > Angular 库 - 使用 APP_INITIALIZER 将参数传递给服务

问题描述

我目前正在创建一个角度库(角度 7)。我需要将一些配置传递给模块,并且还需要调用函数“loadConfig”。问题是我无法在 loadConfig 函数中注入配置的值。

如果我尝试将它添加到 deps 数组并为函数添加一个参数,我会得到一个 nullinjector 错误。

我尝试添加一些控制台日志,在 forRoot 方法中,我得到了配置的值,在 SomeService 中我也得到了正确的配置值。在 loadConfig 中,我总是将配置设置为未定义。使用控制台日志,我发现 forRoot 方法是在 loadConfig 之前执行的,所以我很困惑为什么它不起作用。

你能帮我吗?

export function loadConfig() {
  //some code
  //if I add config as a parameter, the config here is undefined
}

    export class SomeModule {
  public static forRoot(config: any): ModuleWithProviders {
    //if I console log here config is populated
    return {
      ngModule: SomeModule,
      providers: [
        SomeService,
        {
          provide: "config",
          useValue: config,
        },
        {
          provide: APP_INITIALIZER,
          useFactory: loadConfig,
          deps: [], //tried adding config here but get nullinjector error
          multi: true,
        }

      ],
    };
  }
}

export class SomeService {
    constructor(@Inject("config") private config: any) {
        //the config here is populated
    }
}

标签: angularangular-http-interceptorsangular-library

解决方案


我在您的代码中没有看到任何运行正常的主要问题。

我建议您使用InjectionToken存储在全局变量中。

这段代码对我来说就像一个魅力:

export const CONFIG_TOKEN = new InjectionToken('APP_CONFIG');

export function initConfig(config: any) {
  return () => {...}
}

export class SomeModule {
  public static forRoot(config: any): ModuleWithProviders {
    return {
      ngModule: SomeModule,
      providers: [
        {
          provide: CONFIG_TOKEN,
          useValue: config,
        },
        {
          provide: APP_INITIALIZER,
          useFactory: initConfig,
          deps: [CONFIG_TOKEN],
          multi: true,
        }
      ]
    };
  }
}

推荐阅读