场景:父组件发布广播,所有订阅了消息的子组件均可以收到消息
实现:
创建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();
}
}
注:所有已订阅的子组件都可以收到消息