0

I have a global settings service I use across multiple projects. It can grab settings based on a complicated key. To avoid confusion, I created a SettingsKeys class with developer friendly names for those complex keys.

export class SettingsKeys {
  public static showSpecialKey = 'SpecialComplexKey34567898798';
  public static hideSpecialHey = 'HideComplexKey2384785994';

  public static getKey(key: string) {
    return this[key];
  }
}

This setup allows me to access directly keys in my code (SettingsKeys.showSpecialKey) and also use a function to get a key through dynamic means.

I found out that for multiple projects, I needed a different SettingsKeys class for each, because some keys would be needed for one project not for others, and I didn't want to assign keys to a project they don't pertain too. I also learned that I had the same function called at the beginning of each project in my app.component.ts files for initializing config settings based on keys. So I created a function like this inside its own local service to be reused elsewhere:

initConfigurationSettings(configSettings: any) {
  for (const key of Object.keys(configSettings)) {
    configSettings[key] = this.settingsService.getValueByKey(SettingsKeys.getKey(key));
    if (configSettings[key] === undefined) {
      return false;
    }
  }
  return true;
}

I realize that the best course of action would be to have this "local service" be another global service like the aforementioned settings service, but it would require that I insert or inject in that service the current project's SettingsKeys class. I've seen things with providers for useValue, useFactory, etc. Can anyone guide me on what would be the best course of action to do this?

user1100412
  • 699
  • 1
  • 10
  • 22
  • I think you should have a look on InjectionTokens https://www.inversionofcontrol.co.uk/injection-tokens-in-angular/ – MoxxiManagarm Oct 02 '20 at 11:59
  • That article discusses using injection tokens in components. The catch is that I want to inject something into a service so that service's method can be used across components in my application. I might be able to inject the token here, but I would be forced to type out the same function for each component. That's not the best use case. – user1100412 Oct 02 '20 at 12:15
  • An injection token also works for services. – MoxxiManagarm Oct 02 '20 at 12:21
  • Do you have an article you can point to MoxxiManagarm? I wasn't able to find one, which lead me to writing this question. – user1100412 Oct 02 '20 at 13:01
  • I think I found one, where I did a similar solution: https://stackoverflow.com/questions/56653260/angular-providers-for-generic-services/56707222#56707222 – user1100412 Oct 02 '20 at 18:28

0 Answers0