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

编程入门 行业动态 更新时间:2024-10-09 18:21:33
本篇文章主要介绍了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、parentponent.ts

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

3、parentponent.html

<table width="500"> <tr *ngFor="let item of list"> <td> {{item.name}} </td> <td> {{item.age}} </td> <td> {{item.address}} </td> </tr></table><child-one-tag></child-one-tag>

4、child-oneponent.ts

import {Component} from "@angular/core";import {CommonService} from "./common.service";@Component({ selector: "child-one-tag", templateUrl: "child-oneponent.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 }; thismonService.addDateFun(params); params = {}; }}

5、child-oneponent.html

<p-dialog header="弹窗" [(visible)]="display" [width]="300" appendTo="body" modal="modal"> <form #myForm="ngForm" name="myForm"> <p>姓名:<input type="text" name="username" [(ngModel)]="username" pInputText/></p> <p>年龄:<input type="number" name="age" [(ngModel)]="age" pInputText/></p> <p>地址:<input type="text" name="address" [(ngModel)]="address" pInputText/></p> <button pButton label="确定" type="submit" (click)="addInfoFun()"></button> <button pButton label="取消" (click)="hideDialog()"></button> </form></p-dialog><button label="添加" pButton (click)="showDialog()"></button>

以上就是本文的全部内容,希望对大家的学习有所帮助,

  • 0
  • 0
  • 0
  • 0
  • 0

更多推荐

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

本文发布于:2023-06-02 22:42:49,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/457412.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:多个   数据通信   示例   组件

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!