angular4 php,如何使用angular4共享组件通信

这次给大家带来如何使用angular4共享组件通信,使用angular4共享组件通信的注意事项有哪些,下面就是实战案例,一起来看一下。

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

1、公用服务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.tsimport {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

{{item.name}}

{{item.age}}

{{item.address}}

4、child-one.component.tsimport {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

姓名:

年龄:

地址:

89fb15ca1552eac91a0cb49a12ca627c.png

相信看了本文案例你已经掌握了方法,更多精彩请关注php中文网其它相关文章!

推荐阅读:

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值