您的位置:首页 > Web前端 > AngularJS

Angular开发(十三)-服务的基本认识及利用服务实现组件间的通信

2017-05-10 13:04 796 查看
服务本人简单的理解为传统的
javascript
中的方法或者封装好的插件,在
angular
中称为服务,哪个组件需要使用该服务就注入进去(类似传统的方法调用或者插件的使用)

常见服务的使用场景

1、多个组件中出现重复的代码时,把重复的代码提取到服务中实现代码的复用(例如:与服务器通信的数据服务)

2、当组件中掺杂了太多的业务代码和数据处理逻辑时,把这些逻辑封装成服务供组件使用,组件仅仅负责跟UI相关的逻辑(例如:
form
表单的校验,把表单的校验写成服务,注入进来)

3、把共享的数据提取到服务中(例如:一个页面中多次使用的效果)、

4、组件之间的通信

一、创建一个服务

ng new demo 创建一个项目

ng g service 服务文件夹/服务名称

二、现在创建一个
ChidTofatherService
表示子组件传递数据到父组件

改服务中创建一个
list
存储数据,定义一个方法往这个
list
里面追加数据

import { Injectable } from '@angular/core';

@Injectable()
export class ChidTofatherService {
list:string[] = [];
constructor() { }
append(str:any){
this.list.push(str);
}
}


//父组件的ts文件
import { Component, OnInit } from '@angular/core';
//引入创建的服务
import {ChidTofatherService} from "./../service/chid-tofather.service";
@Component({
selector: 'app-father',
templateUrl: './father.component.html',
styleUrls: ['./father.component.css'],
providers:[ChidTofatherService] //模块中依赖的服务,引入后该模块下所有的组件都可以使用(注入服务)
})
export class FatherComponent implements OnInit {
//本组件中的list
list:string[] = [];
//申明引用
constructor(private service:ChidTofatherService) { }

ngOnInit() {
this.list = this.service.list; //把服务里面的list数据赋值给组件的list中
}
}


//父组件的html代码,如果list有数据就循环出来展现
<app-child></app-child>
<ul>
<li *ngFor="let item of list">{{item}}</li>
</ul>


//子组件的ts文件
import { Component, OnInit } from '@angular/core';
import {ChidTofatherService} from "./../service/chid-tofather.service";
@Component({
selector: 'app-child',
templateUrl: './child.component.html',
styleUrls: ['./child.component.css']
})
export class ChildComponent implements OnInit {
inputText:string = "";
constructor(private service:ChidTofatherService) { }

ngOnInit() {
}
add(){
this.service.append(this.inputText);
this.inputText = "";
}
}


//子组件的html代码
<input type="text" [(ngModel)]="inputText"/>
<input type="button" value="新增" (click)="add()"/>
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐