Angular4 Shared Example of Data Communication in Multiple Components

Application scenario, operate unified group data in different components, regardless of which components operate on the data, other components neutralize the effect. This way they have to share a service instance. It is the focus of this time. If different instances, the operation is not the same set of data, then there will be such an effect, want to implement the shared service instance, is in all parent components Priviates : [] Introduced this component, there is no need to introduce again in submas, then they are all service instances in the parent components.

 Import {INJECTABLE} from "@ Angular / Core"; @ INJECTABLE () Export Class CommonService {Public Datelist: Any = [{Name: "Zhang Xuchao", AGE: 20, Address: "Beijing Chaoyang District"}]; constructor () {} adddatefun (data) {this.datelist.push (data);}}   
2, Parent.comPonent.ts

Import {Component, Oninit} from “@ Angular / Core”; import {commonservice} from “./common.service”;// here to operate data through the parent subsidiary service, just introduce services in the parent component. @Component ({Selector: “Parent-Tag”, TemplateURL: “Parent.component.html”, Providers: [CommonService]} Export Class PaRentComponent Implements OnInit {public list: any = []; constructor (private commitservice) {this.list = CommonService.Datelist;} ngonit () {}}
3, Parent.comPonent.html

{{item.age} }
   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 commitservice) {} 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 = {};}} 
4, child-one. Component.ts
5, Child-One.Component.html



The above is all the content of this article, I hope to help everyone, I hope everyone will support Tumi Clouds.

© Copyright Notice
Just support it if you like
comment Grab the couch

Please log in to comment