我正在嘗試創建事件廣播服務。Angular 2:事件廣播服務
這是基本概念,我想實現什麼:
export enum Event {
EVENT_A,
EVENT_B, ...
}
@Injectable()
export class BroadcastService {
private broadcastSubject: Subject<Event> = new Subject<Event>();
public next(event: Event): void {
return this.broadcastSubject.next(event);
}
public subscribe(event: Event, componentCall: Function): void {
this.broadcastSubject.subscribe(
eventValue => {
if(event === eventValue) {
componentCall(); // not possible to call component's method like this
}
}
);
}
}
我知道我不能從服務調用組件的方法是這樣的。我必須以某種方式返回觀察值,並從組件中調用它。我不知道如何實現這一點。
感謝您的任何建議。
SOLUTION
感謝AngularFrance,這裏是爲BroadcastService解決方案:你爲什麼不使用事件
@Injectable()
export class BroadcastService {
private broadcastSubject: BehaviorSubject<Event> = new BehaviorSubject<Event>(0);
public next(event: Event): void {
return this.broadcastSubject.next(event);
}
public subject(event: Event): Observable<Event> {
return this.broadcastSubject.asObservable().filter(e => e === event);
}
}
typescript不支持回調函數,你不能這樣做 – Aravind