Dynamic Module / Service and AOT Configuration

I need some Angular services to be configured dynamically, depending on the runtime switch. A few days before the AOT, I got it to work using the following code:

@NgModule({
  imports: [HttpModule],
  providers: []
})
export class MyModule {
  static forRoot(config: MyConfiguration): ModuleWithProviders {
    return {
      ngModule: MyModule,
      providers: [
        SomeService,
        {
          provide: SomeOtherService,
          useFactory: (some: SomeService, http: Http) => {
            switch (config.type) {
              case 'cloud':
                return new SomeOtherService(new SomethingSpecificForCloud());
              case 'server':
                return new SomeOtherService(new SomethingSpecificForServer());
            }
          },
          deps: [SomeService, Http]
        },

      ]
    };
  }
}

Then in mine AppModuleI would import it as MyModule.forRoot(myConfig).

When I update the CLI and Angular, this no longer compiles because it cannot be statically analyzed. I understand why, but I'm still not sure what the correct way to solve it.

Did I use this approach forRoot()in the first place? How do you write modules so that depending on the runtime switch they generate different services?

+4
source share
1

: , "" factory. :

// Necessary if MyConfiguration is an interface
export const MY_CONFIG = new OpaqueToken('my.config');

// Static factory function
export function someOtherServiceFactory(config: MyConfiguration,some: SomeService, http: Http) {
  switch (config.type) {
    case 'cloud':
      return new SomeOtherService(new SomethingSpecificForCloud());
    case 'server':
      return new SomeOtherService(new SomethingSpecificForServer());
  }
}

@NgModule({
  imports: [HttpModule],
  providers: []
})
export class MyModule {
  static forRoot(config: MyConfiguration): ModuleWithProviders {
    return {
      ngModule: MyModule,
      providers: [
        SomeService,
        { provide: MY_CONFIG, useValue: config },
        {
          provide: SomeOtherService,
          useFactory: someOtherServiceFactory,
          deps: [MY_CONFIG, SomeService, Http]
        },

      ]
    };
  }
}

, , , - .


:

  • CLI Angular.
  • / .
  • enviromnent ( , JS-?).
  • .
  • CLI .

.

+4

Source: https://habr.com/ru/post/1669456/


All Articles