Angular 2 - Including a provider in a service

自闭症网瘾萝莉.ら 提交于 2019-12-20 07:37:45

问题


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?


回答1:


This breaks separation of concerns. What am I misunderstanding?

In order to support instantiating multiple instances of a service (i.e., 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 (i.e., you may need to reconfigure the injector tree).




回答2:


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:

  • What's the best way to inject one service into another in angular 2 (Beta)?


来源:https://stackoverflow.com/questions/36457913/angular-2-including-a-provider-in-a-service

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!