1

I have a client Angular2 app which will be consuming a 3rd party NgModule app requiring config data. I need to make config values available as a static property of a service that gets called within different areas of the 3rd party NgModule.

Client app's App.Module:

    export const MediaConfig: MediaConfigInterface =
    {
        MediaUrlRoot: "XXXXXXXXXXXXXXXXXXXXXX",
        Key: "YYYYYYYYYYYYYYYY"
    };


    //app.module.ts
    import { MediaModule } from '....';
    import { MediaConfig } from './configs';

    @NgModule(
    {
        imports: 
        [
            ...
            //3rd PARTY
            MediaModule.forRoot(MediaConfig),
            ...
        ],
        declarations:[...],
        providers:[...],
        bootstrap:[...]
    })
    export class AppModule { }

3rd party NgModule being imported into client App:

    export const CONFIG_DATA = new OpaqueToken('Config Data');
    export function configHelperFactory(config: MediaConfigInterface) 
    {
        ClientConfigService.ConfigModel = config;
        return ClientConfigService;
    }

    @NgModule({
        imports:[...],
        declarations:[...],
        exports:[...],
        entryComponents:[...],
        providers:[]
    })
    export class MediaModule
    {
        static forRoot(config: MediaConfigInterface): ModuleWithProviders
        {       
            return {
                ngModule: MediaModule,
                providers:
                [
                    ClientConfigService,
                    {
                        provide: CONFIG_DATA,
                        useValue: config
                    },
                    {
                        provide: ClientConfigService,
                        useFactory: configHelperFactory,
                        deps: [CONFIG_DATA]
                    }               
                ]
            };
        }
    }

3rd party NgModules static service containing config data from client app:

    import { MediaConfigInterface} from "../models";

    export class ClientConfigService 
    {
        static ConfigModel: MediaConfigInterface;

        static BuildMediaUrl(id: string) : string
        { 
            return '';
        };      
    }

This approach only works if I import ClientConfigService in any component constructor in the client app (I'm currently importing it in app.component.ts). Importing it in the constructor causes the configHelperFactory in 3rd party NgModule to fire which sets the static property with config data.

This approach works and the client app builds with AOT. The problem is it's a bit of a kludge to set config data in App.Module AND import ClientConfigService in any given component's constructor so the configHelperFactory fires.

Is there a way to pass config data into 3rd party NgModule, populate static service property with config data, and be able to build client app with AOT?

Tom Schreck
  • 5,177
  • 12
  • 68
  • 122

0 Answers0