什么是 Angular 事件总线?
在 Angular 应用中,事件总线(Event Bus)是一种用于组件间通信的模式,尤其适用于非父子组件之间的数据传递。
通过创建一个共享的 EventBusService
,开发者可以实现:
- 跨层级通信(如祖孙组件)
- 解耦组件逻辑
- 集中管理事件类型
📘 扩展阅读:Angular 事件总线设计模式详解
实现步骤 ✅
- 创建事件服务
import { Injectable } from '@angular/core';
import { Subject } from 'rxjs';
@Injectable({
providedIn: 'root'
})
export class EventBusService {
private eventSubject = new Subject<any>();
public events = this.eventSubject.asObservable();
emit(event: any): void {
this.eventSubject.next(event);
}
}
- 发送事件
this.eventBus.emit({ type: 'USER_LOGIN', payload: { username: 'JohnDoe' } });
- 监听事件
this.eventBus.events.subscribe(event => {
if (event.type === 'USER_LOGIN') {
console.log('用户登录:', event.payload.username);
}
});
适用场景 🌐
- 🧩 多组件协同工作(如表单验证与结果显示组件)
- 🔄 状态同步(如全局状态管理替代)
- 📡 通知机制(如操作成功/失败提示)
最佳实践 📌
- ✅ 为事件类型定义枚举(如
enum EventTypes { LOGIN, LOGOUT }
) - ⚠️ 避免过度使用,优先使用
@Input() / @Output()
通信 - 📦 通过
Angular
官方推荐的EventEmitter
实现轻量级通信
可视化示例 📊
代码结构建议 📁
src/
├── app/
│ ├── event-bus.service.ts
│ ├── components/
│ │ ├── header/
│ │ └── footer/
│ └── app.module.ts
🌐 相关技术:Angular 高级通信技巧
🧠 进阶学习:RxJS 在 Angular 中的运用