2

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
    }
}
1
  • your code seems fine, see my answer. But in deps did you pass token 'config' as string or config value. It could be the issue. To avoid any confusion, create a global injection token. Commented Jul 7, 2020 at 12:39

1 Answer 1

2

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,
        }
      ]
    };
  }
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.