0

We have a forRoot in which we conditionally build up a providers array based on conditions in a config object. AOT doesn't like this and returns the error 'function calls are not supported in decorators but 'XxxModule' was called'.

forRoot(config: MyModuleOptions){
    const providers = [
        AService,
        BService
    ];
    // here we check some config options to define which other things we inject
    if(config.behaviorC){
        providers.push(CService);
    }
    return {
        ngModule: MyModule,
        providers: providers
    };
}

How can we fix this or use another approach to avoid the AOT error?

stephan.peters
  • 963
  • 13
  • 35

1 Answers1

0

You can use a factory and return null in case the condition fails like so:

import { NgModule, ModuleWithProviders, Injector } from '@angular/core';
import { CoreModuleOptions } from './core.module-options';
import { CoreService } from './core.service';

export function coreServiceFactory(injector: Injector, options: CoreModuleOptions){
    return options.condition ? new CoreService() : null;
}

@NgModule({
})
export class CoreModule {
    static forRoot(config?: CoreModuleOptions): ModuleWithProviders {
        return {
            ngModule: CoreModule,
            providers: [
                {
                    provide: CoreModuleOptions,
                    useValue: config
                },
                {
                    provide: CoreService,
                    useFactory: coreServiceFactory,
                    deps:[ Injector, CoreModuleOptions]
                }
            ]
        };
    }
}
stephan.peters
  • 963
  • 13
  • 35