1.EventEmitter
公共服务中定义事件发送方法
1.1 全局事件发射器
public commonEvent = new EventEmitter();
1.2 发送事件方法
sendCommonEvent(name: string, value) {
this.commonEvent.emit({name, value});
}
1.3 监听事件方法
watchCommonEvent(name: string) {
return this.commonEvent.pipe(
filter((item) => item.name === name), // 监听事件名
map((item) => item.value) // 映射事件发送的值
);
}
组件中使用
组件A发送
this.service.sendCommonEvent('changeId', id);
组件B监听
this.service
.watchCommonEvent('changeId')
.subscribe((id) => {
// console.log(id)
});