一直在WPF-Prism框架中寻找类似于 IEventAggregator 的东西 .
This在我看来有点同样的问题,除了在Angular 5中寻找解决方案 .
到目前为止找不到简单的解决方案 . 不得不使用 typescript generics , angular dependency injection 使用服务和 "rxjs/Subject" 自己创建一个 .
它主要受this帖子的启发 .
创建名为 EventService
的服务并将其注册为 AppModule
中的依赖项 . 由于它被添加到 AppModule
AppModule
列表中,因此可以将其解析为任何组件中的依赖项 .
EventService:
/**
* For inter component communication throughout application.
* Use dependency injection to raise an event with payload.
* NOTE: All subscriptions to be unsubscribed at ngOnDestroy() method of subscribing component
*/
@Injectable()
export class EventService {
private someDataChangeEvent: IEvent<string> = new Event<string>();
constructor() { }
public get someDataChange(): IEvent<string> {
return this.userImageChangeEvent;
}
}
其中IEvent和Event是:
import { Subscription } from "rxjs";
import { Subject } from "rxjs/Subject";
export interface IEvent<T> {
/**
* Method which will signal the subscribers.
* @param payload
*/
publish(payload: T): void,
/**
* Registers the payload receiving function.
* NOTE: Subscribing component should handle the subscription disposal on ngOnDestroy method.
* @param callback: callback function
*/
subscribe(callback: (payload: T) => void): Subscription
}
export class Event<T> implements IEvent<T> {
private subject = new Subject<any>();
constructor() { }
public publish(payload: T): void {
// Notify subscribers.
this.subject.next(payload);
}
public subscribe(callback: (payload: T) => void): Subscription {
// Create a subscription with the passed callback
let subscription = this.subject.asObservable().subscribe(callback);
return subscription;
}
}
在发布组件
1.Constructor - 解决依赖:
constructor(
private readonly _eventService: EventService
) { }
- 数据更改时发布事件 . 比如说,httpClient完成或下拉项目更改或按钮单击 .
payload
是您要发送给订阅组件的数据 .
self._eventService.someDataChange.publish(payload);
现在,在订阅组件
-
实现OnInit和OnDestroy
-
构造函数 - 解决依赖关系,与上面相同
-
在ngOnInit方法中,订阅事件
-
在ngOnDestroy取消订阅订阅中 .
export class SomeComponent implements OnInit, OnDestroy {
constructor(
private readonly _eventService: EventService
) { }
private eventSubscription: Subscription = null;
ngOnInit() {
this.eventSubscription = this._eventService.someDataChange.subscribe((payload) => {
// Do something with payload
});
}
ngOnDestroy() {
this.eventSubscription.unsubscribe();
}
}
我可以定义与应用程序需求一样多的不同事件,并且多个组件可以订阅这些事件 . 但是我需要在ngOnDestroy方法中小心处理所有这些订阅 .
有没有办法避免它?有没有办法自动删除订阅,在组件销毁时没有明确地执行它 .
在应用程序中有一个或两个事件,这很好 . 但是在 EventService
中注册了10多个事件,多个组件订阅了大部分事件,我怀疑这是一个很好的解决方案吗?
我有什么选择?至少,自动取消订阅处理组件将是一个很大的帮助 . 谢谢 .