组件之间的通信(EventEmitter)

界面是由N多个组件组成,如果一个组件中修改了接口的内容,其他组件需要调接口刷新数据

myService.ts:

import {Component,Injectable,EventEmitter}from'@angular/core';

@Injectable()

export class myService {

    change: EventEmitter;

    constructor(){

        this.change =new EventEmitter();//定义发射事件

    }

}

parent.html:

{{num}}

parent.ts:

import { Component }from'@angular/core';

import{myService}from'../child/myService'

export class ParentPage {

    num:number =0;

    constructor(public service:myService) {

          发射一:service.change.emit(++this.num);//发射

    }

//发射二

someFunc(){

    this.service.change.emit(num);

}

}

child.html:

{{num}}

child.ts:

import { Component, EventEmitter}from'@angular/core';

import{myService}from"../child/myService"

export class ChildPage {

    num:number =0;

    constructor(public service:myService){

        service.change.subscribe((value:number)=>{

            this.num = value;//接收

        })

    }

}

你可能感兴趣的:(组件之间的通信(EventEmitter))