How to provide an injectiontoken to an injectable service

55 Views Asked by At

I have a module with a service that I am sharing

@Injectable({providedIn: 'root'})
export class SharedService{
    constructor(
        private store: Store,
        @Inject(API_REQUESTS) private apiRequests: ApiRequestInterface[]
    ) {
        debugger;
    }

As you can see I want to be able to pass in a list of API requests into this service so in my shared module I configured the following:

export const API_REQUESTS = new InjectionToken<ApiRequestInterface[]>('ApiRequests');

@NgModule({
    declarations: [],
    providers: [],
    imports: [
        CommonModule,
        NgxsModule.forFeature(
            [
                ApiState
            ]
        )
    ]
})

export class ApiModule {
    constructor(@Optional() @SkipSelf() parentModule: ApiModule ) {
    }

    static forRoot(apiRequests?: ApiRequestInterface[]): ModuleWithProviders<ApiModule> {
        return {
            ngModule: ApiModule,
            providers: [
                {provide: API_REQUESTS, useValue: apiRequests}
            ]
        };
    }
}

And in the implementing module I define

 providers: [
   SharedService
 ],
 imports: [
   ApiModule.forRoot([])
 ]

but when I use the SharedService in my components of my implementing module I am getting:

NullInjectorError: No provider for InjectionToken ApiRequests

What am I missing ?

0

There are 0 best solutions below