Home > Software design >  Angular service keeps saying NullInjectorError: No provider for anotherService
Angular service keeps saying NullInjectorError: No provider for anotherService

Time:02-16

I created simple angular service

@Injectable()

export class someHandler {

    constructor(
        public anotherService: anotherService,
    ) {}
...

Problem is that when I use this service in some component it keeps saying that NullInjectorError: No provider for anotherService but I cant use providers: [] inside service right? So what can I do? Thanks for any help.

CodePudding user response:

Not sure because you didn't provide the module.ts but looks like anotherService is not part of the same module as someHandler.

In the module where you defines providers : ['someHandler']

You must import the module that include anotherService -> imports: [..., anotherServiceModule]

CodePudding user response:

We must tell Angular to instantiate AnotherService to be available (instatiated) before SomeHandler. So in your module:

@NgModule({
  declarations: [
    AppComponent,
    Component1Component
  ],
  imports: [
    BrowserModule,
    FormsModule,
    HttpModule
  ],
  providers: [AnotherService],
  bootstrap: [AppComponent]
})
export class AppModule { }

Like this, AnotherService is provided to the entire application as singleton and it is already instantiated.

  • Related