Angular 2 - 在服务中包含提供者 [英] Angular 2 - Including a provider in a service

查看:37
本文介绍了Angular 2 - 在服务中包含提供者的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个服务作为提供者加载到组件中.该服务可能会使用 Http 返回数据,也可能不会,组件不应该关心.但是,如果加载的服务使用 Http,则组件本身似乎必须包含 HTTP_PROVIDERS.这打破了关注点的分离.我有什么误解?

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?

推荐答案

这打破了关注点的分离.我有什么误解?

This breaks separation of concerns. What am I misunderstanding?

为了支持实例化一个服务的多个实例(即,所有服务都不必是单例),Angular 应用程序需要一种方法来指定多个注入器(不仅仅是一个).这些注入器需要在某种层次结构中创建和配置.组件/指令树,因为它是一棵树,已经有一个层次结构.所以 Angular 使用(现有的)组件树来配置依赖注入.我喜欢将其视为覆盖组件树的稀疏注入器树".

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.

我认为为服务定义一个单独的层次结构会做更多的工作 -ndash;作为开发人员,我们可能需要定义和配置某种类型的另一个注入器树.

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.

因此,与其将其视为组件需要了解服务的依赖关系"(这样说,听起来确实像我们打破了关注点分离),我更喜欢将其视为以下内容:当我编写一个 Angular 应用程序时,我必须在注入器树上配置我的提供者/依赖项"......并且由于注入器树覆盖了组件树,我使用组件来配置它.

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.

但这并不理想,因为如果您想在不同的应用程序中重用组件,您可能需要更改 providers 数组(即,您可能需要重新配置注入器树).

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).

这篇关于Angular 2 - 在服务中包含提供者的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆