Miigueel
Miigueel

Reputation: 153

Angular Library - Pass parameter to service with APP_INITIALIZER

I'm currently creating an angular library (angular 7). I need to pass a few configurations to the module and I also need to call the function "loadConfig". The problem is I can't inject the value of the configuration in the loadConfig function.

If I try to add it to the deps array and add a parameter to the function, I'll get a nullinjector error.

I tried adding some console logs and inside the forRoot method, I get the value of the config, and in the SomeService I also get the correct value of the config. Inside loadConfig I always get the config as undefined. Using the console logs, I found out the forRoot method is executed before the loadConfig, so I'm confused why it isn't working.

Can you help me, please?

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
    }
}

Upvotes: 2

Views: 1656

Answers (1)

Thierry Falvo
Thierry Falvo

Reputation: 6300

I don't see any main issue in your code which is working fine.

I recommend you to use InjectionToken stored in a global variable.

This code is working like a charm on my side:

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,
        }
      ]
    };
  }
}

Upvotes: 2

Related Questions