应用场景,不同组件中操作统一组数据,不论哪个组件对数据进行了操作,其他组件中立马看到效果。这样他们就要共用一个服务实例,是本次的重点,如果不同实例,那么操作的就不是同一组数据,那么就不会有这样的效果,想实现共用服务实例,就是在所有父组件中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.ts

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

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

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

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

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

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

华山资源网 Design By www.eoogi.com
广告合作:本站广告合作请联系QQ:858582 申请时备注:广告合作(否则不回)
免责声明:本站资源来自互联网收集,仅供用于学习和交流,请遵循相关法律法规,本站一切资源不代表本站立场,如有侵权、后门、不妥请联系本站删除!
华山资源网 Design By www.eoogi.com

稳了!魔兽国服回归的3条重磅消息!官宣时间再确认!

昨天有一位朋友在大神群里分享,自己亚服账号被封号之后居然弹出了国服的封号信息对话框。

这里面让他访问的是一个国服的战网网址,com.cn和后面的zh都非常明白地表明这就是国服战网。

而他在复制这个网址并且进行登录之后,确实是网易的网址,也就是我们熟悉的停服之后国服发布的暴雪游戏产品运营到期开放退款的说明。这是一件比较奇怪的事情,因为以前都没有出现这样的情况,现在突然提示跳转到国服战网的网址,是不是说明了简体中文客户端已经开始进行更新了呢?