Daniel Grima
Daniel Grima

Reputation: 2825

Angular 2 must use @Inject(forwardRef(...)) for Service to be injected

I have an issue with one service within my application. The issue is that wherever this service is being injected I'm getting the following error:

Uncaught (in promise): Error: Can't resolve all parameters for TestComponent: ([object Object], ?, [object Object])

I know that this issue could be caused because of the use of barrels however I'm not using barrels for services, but referencing the file "directly" for example: ../../core/services/config.service.

As suggested in this answer I tried to use @Inject(forwardRef(...)) wherever this service is being injected. The only exception I have is the AppComponent where in this case I'm injecting the same service "normally" and I get no error:

export class AppComponent implements OnInit {
    constructor(
        private configService: ConfigService, // NO ERROR
        private router: Router
    ) { }

    ...

}

In all the other places if I don't do something like the following I get the error described above:

export class BuyButtonComponent {
    constructor(
        @Inject(forwardRef(() => ConfigService)) private configService: ConfigService,
        // private configService: ConfigService // DOES NOT WORK
    ) { }

    ...

}

It is my understanding that forwardRef() is used when the dependency is to be injected but not yet defined. The ConfigService is provided from a CoreModule which is imported in the AppModule. The components are either in a SharedModule or a FeatureModule that I have.

Not sure if anyone can shed some light as to why this particular service requires the forwardRef in any component (bar the AppComponent), whilst all other services which are imported and provided in the same manner are injected the "normal way".

Update

Here's how the service is being provided:

CoreModule

@NgModule({
    providers: [
        // Other Services...
        ConfigService
    ]
})
export class CoreModule { }

AppModule

@NgModule({
    bootstrap: [AppComponent],
    imports: [
        BrowserModule,
        FormsModule,
        HttpModule,
        BrowserAnimationsModule,
        CoreModule,
        AppRoutingModule
    ]
})
export class AppModule { }

The ConfigService is provided from the CoreModule and no where else. Also the CoreModule is only imported in the AppModule. The idea is to have services provided from a single module. The service is being used in components that are declared in other modules (SharedModule and a FeatureModule).

Upvotes: 5

Views: 4351

Answers (0)

Related Questions