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

本篇文章主要介绍了angular4 共享服务在多个组件中数据通信的示例,现在分享给大家,也给大家做个参考。

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

1、公用服务

  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.ts

  1. 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

  1.  

登录后复制    {{item.name}}    {{item.age}}    {{item.address}}  

4、child-one.component.ts

  1. 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

  1.   

    姓名:

     

    年龄:

     

    地址:

       

登录后复制

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

上面是我整理给大家的,希望今后会对大家有帮助。

相关文章:

轻量级JS Cookie插件js-cookie的使用方法

p5.js 毕达哥拉斯树的实现代码

JS动画定时器知识总结

以上就是angular4 共享服务在多个组件中数据通信的示例的详细内容,更多请关注【创想鸟】其它相关文章!

声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。

点点赞赏,手留余香

给TA打赏
共0人
还没有人赞赏,快来当第一个赞赏的人吧!
    编程技术

    js将键值对字符串转为json字符串的方法

    2025-3-8 7:20:04

    编程技术

    基于js中的存储键值对以及注意事项介绍

    2025-3-8 7:20:12

    0 条回复 A文章作者 M管理员
    欢迎您,新朋友,感谢参与互动!
      暂无讨论,说说你的看法吧
    个人中心
    购物车
    优惠劵
    今日签到
    私信列表
    搜索