国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 編程 > JavaScript > 正文

angular4 共享服務(wù)在多個組件中數(shù)據(jù)通信的示例

2019-11-19 14:04:59
字體:
供稿:網(wǎng)友

應(yīng)用場景,不同組件中操作統(tǒng)一組數(shù)據(jù),不論哪個組件對數(shù)據(jù)進(jìn)行了操作,其他組件中立馬看到效果。這樣他們就要共用一個服務(wù)實例,是本次的重點(diǎn),如果不同實例,那么操作的就不是同一組數(shù)據(jù),那么就不會有這樣的效果,想實現(xiàn)共用服務(wù)實例,就是在所有父組件中priviates:[]中引入這個組件,子組件中不需要再次引入,那么他們都是用的父組件中的服務(wù)實例。

1、公用服務(wù)

import {Injectable} from "@angular/core";@Injectable()export class CommonService { public dateList: any = [ {  name: "張旭超",  age: 20,  address: "北京市朝陽區(qū)" } ]; constructor() { } addDateFun(data) { this.dateList.push(data); }}

2、parent.component.ts

import {Component, OnInit} from "@angular/core";import {CommonService} from "./common.service";// 這里要通過父子公用服務(wù)來操作數(shù)據(jù),只需要在父組件中引入服務(wù)。@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>

以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持武林網(wǎng)。

發(fā)表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發(fā)表
主站蜘蛛池模板: 安义县| 盐山县| 临夏市| 冷水江市| 客服| 新绛县| 太白县| 桂林市| 油尖旺区| 长岛县| 德化县| 彝良县| 栾城县| 喀喇沁旗| 太和县| 齐齐哈尔市| 越西县| 河曲县| 兴仁县| 亳州市| 平利县| 湘乡市| 苏尼特左旗| 瑞丽市| 宝山区| 湘潭市| 柳江县| 稻城县| 东城区| 保定市| 依兰县| 武川县| 扬中市| 固阳县| 延安市| 金门县| 犍为县| 隆林| 杭州市| 泰顺县| 平果县|