-1

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.

Matt
  • 699
  • 5
  • 15

1 Answers1

1

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.

  • Hi thanks for you answer, I do import MyModule though I indeed forgot to show that in my question. Making a minimal reproducible example in stackblitz has proven impossible because everything seems to work fine there, so I deleted the `.angular` folder and rebuilt the whole project and now it is no longer undefined. Just one of those magic corrupted built cache problems I guess... – Matt Aug 14 '22 at 17:21
  • I'll still accept your answer though, it might help someone who forgets to import their feature module. – Matt Aug 14 '22 at 17:22
  • Thanks! Sometimes this situation can happen and re-creating the project can also help :) – Yevhen Bodnia Aug 14 '22 at 17:30