简体   繁体   中英

Angular 2 - Including a provider in a service

I have a service loaded into a component as a provider. This service may return data using Http or it may not, the component should not care. However, it seems that the component itself must include HTTP_PROVIDERS if the loaded service uses Http. This breaks separation of concerns. What am I misunderstanding?

In fact, it's better to specify the HTTP_PROVIDERS when bootstrapping your application:

bootstrap(AppComponent, [ HTTP_PROVIDERS ]);

But I agree with you that there are some impacts on having configuration of providers only on components.

The previous configuration will work because of hierarchical injectors.

See this question for more details about hierarchical injectors:

This breaks separation of concerns. What am I misunderstanding?

In order to support instantiating multiple instances of a service (ie, so all services don't have to be singletons), an Angular app needs a way to specify multiple injectors (not just one). These injectors need to be created and configured in some kind of hierarchy. The component/directive tree, since it is a tree, already has a hierarchy. So Angular uses the (existing) component tree to configure dependency injection. I like to think of it as a sparser "injector tree" that overlays the component tree.

I think it would be more work to define a separate hierarchy for services – we, as developers, would probably have to define and configure another injector tree of some sort.

So instead of thinking of it as "components need to know the dependencies of services" (which, when stated that way, it does sound like we're breaking separation of concerns), I like to think of it more like the following: "when I write an Angular app, I have to configure my providers/dependencies on the injector tree"... and since the injector tree overlays the component tree, I use components to configure it.

But this is not ideal, since if you want to reuse components in a different app, you might need to change the providers arrays (ie, you may need to reconfigure the injector tree).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM