我通常使用带有主题的服务
import {Injectable} from '@angular/core';
import {Observable, Subject} from "rxjs";
/**
* Event Types
*/
export const MyAppEventTypes =
{
EventType1: 'EventType1'
//...
};
/**
* Events
*/
export class MyAppEvent
{
type: string;
data: any;
}
/**
* Service in charge of broadcasting messages
*/
@Injectable()
export class MessageService
{
/**
* Subject to trigger events
* @type {Subject<MyAppEvent>}
*/
private myAppEventSubject: Subject<MyAppEvent> = new Subject<MyAppEvent>();
/**
* The observable for events
* @type {"../../Observable".Observable<MyAppEvent>}
*/
public readonly myAppEvent$: Observable<MyAppEvent> = this.myAppEventSubject.asObservable();
/**
* Broadcasts a message
* @param name
* @param data
*/
broadcast(name: string, data)
{
this.myAppEventSubject.next(
{
type: name,
data: data
});
}
}
然后,在一个需要广播消息的类中,注入服务后
this.messageService.broadcast(MyAppEventTypes.EventType1, {data: 'test'});
并在需要接收消息的类中,注入服务后
this.messageService.myAppEvent$.subscribe(ev => {
if (ev.type == MyAppEventTypes.EventType1)
{
this.data = ev.data;
}
});