简体   繁体   English

当我们拥有组件时,为什么需要服务?

[英]Why do we need services when we have components?

I am learning Angular and I am struggling to understand the application of Services. 我正在学习Angular,并且正在努力了解Services的应用程序。 I understand services are for reusability but that can be acheived by Components, too. 我知道服务是为了可重用性,但是组件也可以实现。 Also, we can make components public and share also. 另外,我们可以公开组件并共享。 So why exactly do we need services? 那么,为什么我们需要服务呢?

Services don't have a view associated with them (no html and css). 服务没有与之关联的视图(没有html和CSS)。 Less overhead. 更少的开销。 Also, Services can be reused anywhere without needing to create a new instance of the service. 同样,可以在任何地方重用服务,而无需创建服务的新实例。 This is invaluable if you want to share data or functions globally (or across many different components/contexts). 如果要全局(或在许多不同的组件/上下文中)共享数据或功能,这将是无价的。 With components, you -can- share the same instance of a component with other components in your app using dependency injection, but you can only share that instance with components that are descendants of the component you want to share. 使用组件,您可以使用依赖注入将组件的同一实例与应用程序中的其他组件共享,但是您只能与属于您要共享的组件后代的组件共享该实例。 This is pretty limiting. 这是相当有限的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 为什么我们需要全方位的服务 - Why do we need services in angular 我们什么时候需要在 Angular2 的服务上使用 @Injectable? - When do we need to use @Injectable on our services in Angular2? 为什么我们必须将组件放在声明数组中? - Why do we have to put components in the declarations array? 为什么我们需要 ngrx/store 即使我们可以使用服务和 localStorages? - Why do we need ngrx/store even we can use services and localStorages? 为什么我需要在routerLink中添加“ /”,但在路由器定义中却没有“ /”? - Why I need to add '/' to routerLink but we do not have '/' in router definination? 为什么我们需要`ngDoCheck` - Why do we need `ngDoCheck` 当我们实际上可以在不使用装饰器的情况下注入服务时,为什么要使用 @Injectable() 装饰器? - Why do we use @Injectable() decorator , when we can actually inject services without using the decorator as well? 使用状态管理器时,我们是否需要在组件中存储其他数据? - When using state manager, Do we need to store additional data in components? 我们定义路由时只需要RouterModule吗? - Do we only need the RouterModule when we define routes? 在 Angular 中的组件之间共享数据:我们总是需要 Observables 吗? - Sharing data between components in Angular: do we always need Observables?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM