Angular - 跨组件间的数据广播通信

场景:父组件发布广播,所有订阅了消息的子组件均可以收到消息

实现:

        创建service: WorkerService.component.ts

import { EventEmitter, Injectable, } from "@angular/core";
@Injectable({
    providedIn: 'platform'
})
export class WorkerService {
    constructor() { }
    public eventbus: EventEmitter<any> = new EventEmitter<any>();
}

        发布消息:(父组件)

import { WorkerService } from './service/WorkerService.component';
export class Parent {
    constructor(private _workerService: WorkerService) { };

    sendMsg() {
        this._workerService.eventbus.emit({ type: "parent ", msg: "父组件广播的消息"})
    }
}

注:发消息时,为方便子组件判断接收到的消息类型,及时做出相应的动作,建议发送的消息为JSON类型,用type作为判断依据,当然,你也可以任意定义发送的消息

        接收消息:(已订阅的子组件)

import { WorkerService } from "./service/WorkerService.component";
export class Children_first {
    constructor(private _workervice: WorkerService) {
        this._workervice.eventbus.subscribe(_event => {
            // _event为父组件广播时传出的参数
            if (_event.type == "parent") {
                console.log(_event.msg)
            }
        })
    }
}
import { WorkerService } from "./service/WorkerService.component";
export class Children_second {
    constructor(private _workervice: WorkerService) {
        this._workervice.eventbus.subscribe(_event => {
            if (_event.type == "parent") {
                console.log(_event.msg)
            }
        })
    }
}

注:所有已订阅的子组件都可以收到消息

上一篇:Guava的EventBus


下一篇:TornadoFx的EventBus使用