4

I'm writing an Angular library where I need to pass in a configuration object in the .forRoot() of the module import.

I'm trying to do this (the apparently correct way) with InjectionToken, but getting an AoT compilation error.

Error when compiling with AoT:

error TS4050: Return type of public static method from exported class has or is using name 'InjectionToken' from external module "/path/to/node_modules/@angular/core/src/di/injection_token" but cannot be named.

Any help is appreciated.

module.ts:

import { NgModule } from '@angular/core';
import { CONFIG, Config } from './config';

@NgModule({ ... })
export class SomeModule {
    static forRoot(config?: Config) {
        return {
            ngModule: SomeModule,
            providers: [
                { provide: CONFIG, useValue: config }
            ]
        };
    }
}

config.ts:

import { InjectionToken } from '@angular/core';

export const CONFIG = new InjectionToken<Config>('config');

export interface Config {
    some?: string;
    values?: string;
    here?: string;
}

Desired usage by another application:

import { NgModule } from '@angular/core';
import { SomeModule } from 'some-library';

@NgModule({
    imports: [
        SomeModule.forRoot({
            // <-- config values here
        })
    ]
})

(Angular 5, TypeScript 2.6.2)

Mike
  • 4,071
  • 21
  • 36

1 Answers1

2

Answer by JB Nizet in comments above...

Needed to specify the type returned by the forRoot method, ModuleWithProviders.

import { NgModule } from '@angular/core';
import { CONFIG, Config } from './config';

@NgModule({ ... })
export class SomeModule {
    static forRoot(config?: Config): ModuleWithProviders {
        return {
            ngModule: SomeModule,
            providers: [
                { provide: CONFIG, useValue: config }
            ]
        };
    }
}
Mike
  • 4,071
  • 21
  • 36