Angular2初级篇之component和service
来源:互联网 发布:打印快递单用什么软件 编辑:程序博客网 时间:2024/06/13 04:40
为什么使用组件(component)
根据前两篇文章做成的项目,我们的界面现在全部在app.component.html。若我们的界面不断增大就会导致我们的app.component.html越来越大,且不善于复用。于是用到了组件,来进行拆分。此处将展示基本用法。
组件讲解:
1、给相应的组件起名字
我们的所有组件名都以Component结尾。所有组件的文件名都以.component结尾。
这里我们使用小写中线命名法 (也叫烤串命名法)拼写文件名, 所以不用担心它在服务器或者版本控制系统中出现大小写问题。
2、在component.ts中必需导入的模块Component(必须导入)
3、我们使用@Component装饰器创建元数据。在元数据中,我们指定 选择器(selector)的名字,用以标识此组件的元素。指定模板地址(templateUrl:xx.html)或 模板(template:[``])以及 样式地址(styleUrl:xx.css)或样式(style:[``])。 然后,我们导出这个 类(export class 类名),以便其它组件可以使用它。
做完这些,我们把它导入AppComponent组件,并创建相应的<selector起的名字>元素。
做完这些,我们把它导入AppComponent组件,并创建相应的<selector起的名字>元素。
组件调用:
1、修改app.module.ts在@NgModule的declarations[]中添加相应的组件(导出的类)
2、在其他界面调用<my-app></my-app>
为什么使用服务(service)
现阶段我们的逻辑处理都写在了组件的类里面,随着业务的增加文件中代码的增长量会很大,这在实际项目中是不合适的。类中应该只做逻辑处理的调用。所以应用到了服务来做逻辑的处理。
服务讲解:
1、给服务起名字
服务名称的小写形式(基本名),加上.service后缀。 如果服务名称包含多个单词,我们就把基本名部分写成中线形式 (dash-case)。 例如,SpecialSuperHeroService服务应该被定义在special-super-hero.service.ts文件中。
2、导入Injectable函数,并作为@Injectable()装饰器使用这个函数
服务调用:
1、全局调用
1)、将服务导入到app.module.ts中,并在@NgModule的providers[]添加服务
2)、在组件中使用
2、组件调用
1)、将服务代码从app.module.ts中拿出放到相应组件的@Component中
2)、调用方式同上
现在你可以更改自己的项目了~
参考:Angular2中文版
0 0
- Angular2初级篇之component和service
- Angular2初级篇之路由
- Angular2初级篇之环境搭建
- Angular2初级篇之主从结构
- Angular2源码解读之Component
- Angular2 series – Component, Directive, Pipe and Service
- @Repository、@Service、@Controller 和 @Component
- @Repository、@Service、@Controller 和 @Component
- @Component 、@Repository、@Service 和 @Controller
- @Repository、@Service、@Controller 和 @Component
- @Repository、@Service、@Controller 和 @Component
- @Repository、@Service、@Controller 和 @Component
- @Repository、@Service、@Controller 和 @Component
- @Repository、@Service、@Controller 和 @Component
- @Repository、@Service、@Controller 和 @Component
- @Repository、@Service、@Controller 和 @Component
- @Repository、@Service、@Controller 和 @Component
- @Repository、@Service、@Controller 和 @Component
- 安卓手机常见问题汇总
- HTTP请求原理介绍
- 各种排序算法的分析及java实现
- JAVA基础篇 ,类 对象,,封装 , 继承 的抽象思想
- MATLAB遗传算法实例
- Angular2初级篇之component和service
- 【算法概论】7.线性规划与规约
- Queue Reconstruction by Height
- SSM框架——详细整合教程(Spring+SpringMVC+MyBatis)
- Android定制--------调用SystemProperties编译器报错
- 【hadoop】大规模中文网站聚类kmeans的mapreduce实现(上)
- Java中的几种排序方法
- solrj优化的问题(filtercache)
- 《Reverse Engineering for Beginners》 - 第1章 代码模式 - 笔记(1.7)