【发布时间】:2016-12-06 22:05:12
【问题描述】:
我有一个“appService”,用于处理所有组件(表单、导航等)之间的交互。
我的服务有许多组件订阅的事件发射器(结果显示、元素选择、表单发布等)。
当显示一个新视图时,它会订阅它需要的 appService 事件。现在的问题是当我导航到另一个视图(表单)时,不再需要的视图被破坏,但它的订阅仍然被调用......!我发现引用所有订阅和明确取消订阅对于一项简单的任务来说是一个巨大的样板。我究竟做错了什么?如何简化这个?
示例代码:
export class VendorsForm {
constructor(private appService: AppServiceMain)
{
this.appService.onSearchResultSelected$.subscribe((selectedEntity) => {
//detailed view of this item
this.model = selectedEntity;
this.appService.setFormIsShowingDetail();
})
});
}
}
现在在另一个组件中:
export class CustomersForm {
constructor(private appService: AppServiceMain)
{
this.appService.onSearchResultSelected$.subscribe((selectedEntity) => {
//detailed view of this item
this.model = selectedEntity; this.appService.setFormIsShowingDetail();
})
});
}
}
作为参考,这里是服务和事件调用组件:
export class AppServiceMain {
public onSearchResultSelected$: EventEmitter<IEntity>;
setSelectedEntity(ent: IEntity)
{
this.formstate = states.EntitySelected;
this.onSearchResultSelected$.emit(ent);
}
事件调用组件
export class ResultsComponent {
rowDblClick(ev$)
{
this.appService.setSelectedEntity(ev$.data);
}
如果我愿意,我确实知道如何删除这些订阅。问题是我的表单非常大而且功能强大,而且我有大量的非标准参考,难道没有办法在视图被破坏时自动停止收听吗?我发现手动销毁所有这些非常容易出错。
【问题讨论】:
-
小备注:我的ResultsComponent 和appService 都始终是活动的并且是单个实例
-
您能否说明为什么实现
ngOnDestroy方法对您不起作用?如果您错过了:OnDestroy
标签: angular observable subscription eventemitter ondestroy