Feature: Option to prevent child component access to parent component injector
My understanding of DI in Angular 2 is that the system will attempt to satisfy dependencies for injected services in a component's constructor by first querying the component's own injector (which may or may not have the relevant provider explicitly available) and, if no provider is found, to kick the request up the chain until a parent/ancestor component injector is found that contains a provider that satisfies the dependency (if no such provider is found, an error is thrown).
To the best of my knowledge, there is no way to prevent this default behaviour. I would therefore like for it to be possible to restrict the availability of a provided service for injection to only the component it is specifically provided for. The implicit access to ancestral injectors and therefore providers is not always desirable.
I think you're looking for @Self
Hi Eric,
Thank you very much for that! It is very nearly what I want, but I was hoping for something on the parent's side so that all children are automatically "disowned" so to speak :)
Did you try viewProviders?
Do you have a concrete use case?
viewProviders: [provide(SomeService, {useValue: null})]
might work.
Thank you very much for the input, I have not tried the 'viewProvider' approach yet, but read what I could find on it and it seems like it might indeed be what I am looking for.
@zoechi I don't have a specific use case, my issue is more one of architecture and modularisation. My preference is to default to restricted access so, unless a component needs access to a service, it shouldn't have access to that service. Having said that, I am still new to Angular so if you know of a reason why this should not be a concern to me, I would appreciate the education :)
unless a component needs access to a service, it shouldn't have access to that service
@williamhallatt if that's your preference I think the parent to child approach is not the best one. Suppose you have three children, of which only one must NOT have access to the parent's service, if you pass null you will affecting the three of them. So it is better imo to use @Self, so let the child to handle if it should have access to the parent's service, or simply ignore it.
Valid point. Thank you!
This issue has been automatically locked due to inactivity. Please file a new issue if you are encountering a similar or related problem.
Read more about our automatic conversation locking policy.
This action has been performed automatically by a bot.