0

I have declaration of providers in app module which provides list of implementations of MyProviderService class (I am using multi: true). Now I would like to "undefine" this list in one component completely, so I added:

@Component({
  providers: [
    { provide: MyProviderService, useValue: undefined },
  ],
})

That works and injector has empty value for the MyProviderService. I am wondering if there is a way to remove the MyProviderService from injector completely. Something that would later require to mark the service as @Optional in the constructor for DI.

sax
  • 808
  • 1
  • 12
  • 25

1 Answers1

1

No, there is no possibility to nullify one of the provided things. Injectors refer to the parent injector, if some token is not found in their scope, otherwise it is found and returned back to the querying code.

However you can spawn a component with a newly created injector that has no link to parent injector. In this case there will be no any items available in the corresponding DI subtree, and there will be not possible to inject other items as well.

Andrei
  • 10,117
  • 13
  • 21
  • I think new injector would be more trouble than gain as I would have to provide dependencies for other child components and that would be hard to maintain in a long term. I will stick to the provider with undefined value. Thanks for your answer! – sax Sep 01 '22 at 08:04