首页 > 其他 > 详细

angular4 父组件和子组件通过服务来通讯

时间:2017-12-10 23:38:07      阅读:394      评论:0      收藏:0      [点我收藏+]

父组件和它的子组件共享同一个服务,可以将这服务理解为全局,同时共用,但是这个服务实例的作用域被限制在父组件和其子组件内,这个组件之外的服务无法访问这个服务。

import { Injectable } from ‘@angular/core‘;
@Injectable()
export class myService {
  list:string[] = [];
  constructor() { }
  append(str:any){
    this.list.push(str);
  }
}
//faher.compnent.ts
import { Component, OnInit } from ‘@angular/core‘; 
import {Service} from "service/
Service.service";
@Component({
selector: ‘app-father‘,
templateUrl: ‘father.component.html‘,
styleUrls: [‘father.component.css‘],
providers:[Service]
(注入服务)
})
 export class FatherComponent implements OnInit {
list:string[] = [];
constructor(
    private service:Service
) { }
ngOnInit() {
  this.list = this.service.list;
} }
//faher.compnent.html

<app-child></app-child> <ul> <li *ngFor="let item of list">{{item}}</li> </ul>

 

//child.compnent.ts
import { Component, OnInit } from ‘@angular/core‘;
import {Service} from "service/child.service";
@Component({
selector: ‘app-child‘,
templateUrl: ‘child.component.html‘,
styleUrls: [‘child.component.css‘] })
export class ChildComponent implements OnInit {
inputText:string = "";
constructor(
private service:Service
) { }
ngOnInit() { }
   add(){
  this.service.appeend( this.inputText);
   this.inputText = "";
} }
//child.compnent.html
<input type="text" [(ngModel)]="inputText"/> 
<input type="button" value="add" (click)="add()"/>


 

angular4 父组件和子组件通过服务来通讯

原文:http://www.cnblogs.com/htuthf/p/8018522.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!