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

时间:2021-02-04 05:40:50

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

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()"/>