场景:父组件发布广播,所有订阅了消息的子组件均可以收到消息
实现:
创建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)
}
})
}
}
注:所有已订阅的子组件都可以收到消息
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。