是的,你可以做到。
只需声明一个在主模块中提供的服务(如果您还没有触及默认值是appModule)。
服务看起来像这样:
import { Injectable } from "@angular/core";
import { Subject } from 'rxjs';
@Injectable()
export class DataService {
private $data = new Subject<CommunicationData>();
public dataReceivedEvent = this.$data.asObservable();
public setDataToSend(data: CommunicationData): void {
this.$data.next(data);
}
}
CommunicationData 是一个接口:
export interface CommunicationData {
eventName: string;
data: any;
}
现在只需将此服务作为 DI 注入到您喜欢的每个组件中。
constructor(
private dataService: DataService
) { }
要从这些组件发送数据,您可以这样做:
private sendData(): void {
this.dataService.setDataToSend({
eventName: 'YourCustomEvent',
data: null //can be anything
});
}
要捕获事件,只需执行以下操作(在组件的 onInit 生命周期中):
this.dataService.dataReceivedEvent
.subscribe(result => {
if(result.eventName === 'YourCustomEvent') {
//foo
} else if (result.eventName === '...') {
// something else
} //and so on
});
通过这种方式,您将只有一个服务来保持所有组件之间的通信。