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

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

问题描述

我有一个作为提供程序加载到组件中的服务.该服务可以使用Http返回数据,也可以不使用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.

我认为,为服务定义一个单独的层次结构会需要做更多的工作–作为开发人员,我们可能必须定义和配置其他某种注入器树.

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天全站免登陆