Angular 库 - 使用 APP_INITIALIZER 将参数传递给服务

标签 angular angular-http-interceptors angular-library

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

如果我尝试将其添加到 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
    }
}

最佳答案

我在您的代码中没有发现任何工作正常的主要问题。

我建议您使用存储在全局变量中的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,
        }
      ]
    };
  }
}

关于Angular 库 - 使用 APP_INITIALIZER 将参数传递给服务,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62774098/

相关文章:

css - Angular2子组件破坏CSS关系

angular - 如何取消/取消订阅 Angular 4+ 中所有待处理的 HTTP 请求

javascript - HTTPInterceptor 没有拦截来自 Angular 中第 3 方小部件的 http 请求

angular - 如何通过热重载在本地使用 Angular 库? [错误: Cannot read properties of null (reading 'firstCreatePass' )]

Angular 库导出模型和库

javascript - 在 Angular 中显示来自 Rest Api 的数据的正确方法

html - 二维数组中的 SelectedIndex

angular - 拦截器不拦截 http POST 请求(Angular 6)

Angular-cli:测试 Angular 包

angular - mat-paginator 长度不起作用。无法设置它