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

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

问题描述

它们在不同的地方声明(声明和提供者).我知道该服务具有@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不同,服务的装饰器不存在. @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+中的Service和Component有什么区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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