Home > Software design >  How to a inject service from a feature module into another service in Angular
How to a inject service from a feature module into another service in Angular

Time:08-15

I have a feature module named MyModule which provides a service named ModalsService, I want to inject this ModalsService into another service named ApiService which belongs to my main application and is marked as being provided in the root

@Injectable()
export class ModalsService { ... }
@NgModule({
  providers: [
    BetterModalsService
  ]
})
export class MyModule { }
@Injectable({
    providedIn: 'root'
})
export class ApiService {
    constructor(
        private modalsService: ModalsService
    ) { }

    ...
}

Everything compiles without error but upon trying to call the ModalsService service from the ApiService I get an error that this.modalsService is undefined. I am also injecting the ModalsService service into some components from the main app which works as expected. This leads me to believe that there is some dependency injection trickery going on that I do not understand.

I've tried to use providers: [ApiService] in my app.module.ts rather than providedIn: 'root' but this makes no difference. Any help would be appreciated.

CodePudding user response:

Your ApiService is working fine because it has { providedIn: 'root' } in its decorator @Injectable. An instance of a class (service) is created according to the Singleton pattern (one instance for the entire application).

While the ModalsService service is provided only in one of our modules - MyModule. In this case, we will have a service instance created if we import its module into our module where the ApiService is located, and it will be used.

So, you have two solutions:

  1. Import the module of the ModalsService (MyModule) into the module of the ApiService and it should work.
  2. Set the { providedIn: 'root' } in the decorator of ModalsService. But I don't recommend this way, it's not the best practice. We use it only in special situations.

I think this should help you.

  • Related