Angular 2+中的服务和组件有什么区别? [英] What's the difference between Service and Component in Angular 2+?

查看:22
本文介绍了Angular 2+中的服务和组件有什么区别?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

它们在不同的地方声明(声明和提供者).我知道该服务有 @Injectable() 注入到使用该服务的组件的构造函数中.但为什么一定要这样呢?为什么不能只在一处申报?有哪些功能可以做而另一个不能?

They are declared in difference places (declarations and providers). I know that service has @Injectable() to be injected to constructor of components that use that service. But why does it have to be this way? Why can't we just declare in one place? What functionalities that one can do that the other cannot?

推荐答案

组件

它基本上是一个带有装饰器 @Component 的类,它告诉 Angular 该类是一个组件.

It is basically a class with a decorator @Component which tells angular that the class is a component.

它们总是与 HTML 模板和一些 CSS 相关联.

They are always associated with an HTML template and some CSS.

当 html 的一部分重复使用类似的功能时,最好将其放入组件中.这个组件可以在任何需要相同功能的地方调用.

When a part of html gets repeated with a similar functionality it is always best to put it into a component. This component can be called where ever the same functionality is required.

服务

它们是整个应用程序中一些常见功能的中心单元.

They are central units for some common functions across the application.

它们是具有函数和成员的简单类.

They are simple classes with functions and members.

用于 - 存在重复代码,访问/存储数据.

Used when - Duplication of code exists, Access/store data.

与@Component 和@Directive 不同,Service 不存在装饰器.@Injectable 仅在组件、指令或其他服务需要使用一项服务时使用.

No decorator exists for Services unlike @Component and @Directive. @Injectable is used only when one service needs to be used by a component, directive or another service.

这篇关于Angular 2+中的服务和组件有什么区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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