應(yīng)用場(chǎng)景,不同組件中操作統(tǒng)一組數(shù)據(jù),不論哪個(gè)組件對(duì)數(shù)據(jù)進(jìn)行了操作,其他組件中立馬看到效果。這樣他們就要共用一個(gè)服務(wù)實(shí)例,是本次的重點(diǎn),如果不同實(shí)例,那么操作的就不是同一組數(shù)據(jù),那么就不會(huì)有這樣的效果,想實(shí)現(xiàn)共用服務(wù)實(shí)例,就是在所有父組件中priviates:[]中引入這個(gè)組件,子組件中不需要再次引入,那么他們都是用的父組件中的服務(wù)實(shí)例。
我們提供的服務(wù)有:做網(wǎng)站、網(wǎng)站制作、微信公眾號(hào)開發(fā)、網(wǎng)站優(yōu)化、網(wǎng)站認(rèn)證、羅甸ssl等。為近千家企事業(yè)單位解決了網(wǎng)站和推廣的問題。提供周到的售前咨詢和貼心的售后服務(wù),是有科學(xué)管理、有技術(shù)的羅甸網(wǎng)站制作公司
1、公用服務(wù)
import {Injectable} from "@angular/core"; @Injectable() export class CommonService { public dateList: any = [ { name: "張旭超", age: 20, address: "北京市朝陽(yáng)區(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
{{item.name}} | {{item.age}} | {{item.address}} |
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
以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持創(chuàng)新互聯(lián)。