Angular Service Dependency Issue

Viewed 49

I have a module in a shared library as follows:

import { NgModule } from '@angular/core';
import { ModalModule } from 'ngx-bootstrap/modal';
import { DialogService } from './dialog.service';
@NgModule({
  imports: [ModalModule.forRoot()],
  providers: [DialogService],
})
export class DialogModule {}

The DialogService is used throughout my application (including in lazy loaded modules) but has a dependency of BsModalService in the ModalModule (declared as a dependency in the module above).

In some places where the DialogService is used, the DialogModule has not been declared as a dependency. Therefore the BsModalService is missing and I get runtime errors.

How do I enforce the DialogModule is declared as a dependency where it is injected?

Ideally, I would get build errors with missing dependencies similar to the strictTemplates compilerOptions. However, I don't get any build issues, only runtime which are hard to spot in a large application.

1 Answers

Since you are mentioning that you have used DialogService without importing the DialogModule. My guess is that dialog service might be having the @injectable decorator saying it is provided in root

@Injectable({ providedIn: 'root' })

If so could you please try making it as follows

@Injectable()

It will remove dialog service from adding to app module and will enforce adding DialogModule to lazy loaded module instead.

Related