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

时间:2022-01-14 22:26:56

I am learning Angular and I am struggling to understand the application of 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?

我正在学习Angular,我正在努力理解服务的应用。我理解服务是为了可重用性,但也可以通过组件实现。此外,我们还可以将组件公开并共享。那么为什么我们需要服务呢?

1 个解决方案

#1


2  

Services don't have a view associated with them (no html and 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.

服务没有与之关联的视图(没有html和css)。减少开销。此外,服务可以在任何地方重用,而无需创建新的服务实例。如果您想要全局共享数据或函数(或跨许多不同的组件/上下文),这是非常宝贵的。使用组件,您可以使用依赖项注入与应用程序中的其他组件共享组件的相同实例,但是您只能与作为要共享组件的后代的组件共享该实例。这是非常有限的。

#1


2  

Services don't have a view associated with them (no html and 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.

服务没有与之关联的视图(没有html和css)。减少开销。此外,服务可以在任何地方重用,而无需创建新的服务实例。如果您想要全局共享数据或函数(或跨许多不同的组件/上下文),这是非常宝贵的。使用组件,您可以使用依赖项注入与应用程序中的其他组件共享组件的相同实例,但是您只能与作为要共享组件的后代的组件共享该实例。这是非常有限的。