angular4 共享服务在多个组件中数据通信的示例

应用场景,不同组件中操作统一组数据,不论哪个组件对数据进行了操作,其他组件中立马看到效果。这样他们就要共用一个服务实例,是本次的重点,如果不同实例,那么操作的就不是同一组数据,那么就不会有这样的效果,想实现共用服务实例,就是在所有父组件中priviates:[]中引入这个组件,子组件中不需要再次引入,那么他们都是用的父组件中的服务实例。

1、公用服务

rush:js;"> import {Injectable} from "@angular/core";

@Injectable()
export class CommonService {
public dateList: any = [
{
name: "张旭超",age: 20,address: "北京市朝阳区"
}
];

constructor() {

}

addDateFun(data) {
this.dateList.push(data);
}
}

2、parent.component.ts

rush:js;"> import {Component,OnInit} from "@angular/core"; import {CommonService} from "./common.service";

// 这里要通过父子公用服务来操作数据,只需要在父组件中引入服务。
@Component({
selector: "parent-tag",templateUrl: "parent.component.html",providers: [
CommonService
]
})
export class ParentComponent implements OnInit {
public list: any = [];

constructor(private commonService: CommonService) {
this.list = commonService.dateList;
}

ngOnInit() {

}
}

3、parent.component.html

rush:xhtml;">

4、child-one.component.ts

rush:js;"> import {Component} from "@angular/core"; import {CommonService} from "./common.service";

@Component({
selector: "child-one-tag",templateUrl: "child-one.component.html"
})
export class ChildOneComponent {
public display: boolean = false;
public username: string = "";
public age: number = 20;
public address: string = "";
constructor(public commonService: CommonService) {

}

showDialog() {
this.display = true;
}

hideDialog() {
this.display = false;
}

addInfoFun() {
let params = {
name: this.username,age: this.age,address: this.address
};
this.commonService.addDateFun(params);
params = {};
}
}

5、child-one.component.html

rush:xhtml;"> display" [width]="300" appendTo="body" modal="modal">
姓名:

年龄:

地址:

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持编程之家。

相关文章

前言 做过web项目开发的人对layer弹层组件肯定不陌生,作为l...
前言 前端表单校验是过滤无效数据、假数据、有毒数据的第一步...
前言 图片上传是web项目常见的需求,我基于之前的博客的代码...
前言 导出Excel文件这个功能,通常都是在后端实现返回前端一...
前言 众所周知,js是单线程的,从上往下,从左往右依次执行,...
前言 项目开发中,我们可能会碰到这样的需求:select标签,禁...