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

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

实现:

        创建service: WorkerService.component.ts

import { Injectable, } from "@angular/core";
import { Subject } from "rxjs";
@Injectable({
    providedIn: 'platform'
})
export class WorkerService {
    constructor() { }
    private _refreshSource$ = new Subject<any>();
    public refreshStream$ = this._refreshSource$.asObservable();
    public refreshSections(event: any) {
        this._refreshSource$.next(event)
    }
}

        发布消息:(父组件)

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

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

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

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

import { WorkerService } from "./service/WorkerService.component";
export class Children_first {
    constructor(private _workervice: WorkerService) {
        this.subscription = this._workervice.refreshStream$.subscribe(_event => {
            // _event为父组件广播时传出的参数
            if (_event.type == "parent") {
                console.log(_event.msg)
            }
        })
    }
    subscription: any;
    /**
     * 避免重复订阅,组件销毁时取消订阅
     */
    ngOnDestroy() {
        this.subscription.unsubscribe();
    }
}
import { WorkerService } from "./service/WorkerService.component";
export class Children_second {
    constructor(private _workervice: WorkerService) {
        this.subscription = this._workervice.refreshStream$.subscribe(_event => {
            if (_event.type == "parent") {
                console.log(_event.msg)
            }
        })
    }
    subscription: any;
    /**
     * 避免重复订阅,组件销毁时取消订阅
     */
    ngOnDestroy() {
        this.subscription.unsubscribe();
    }
}

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

        

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值