我有一个统计应用程序。在我的页面左侧有主题列表,顶部有组列表。主要部分包含与主题和组相关的统计项目。
我还有几个服务为我的应用程序提供业务逻辑。为了简单起见,我们来谈谈其中的三个:主题服务、群组服务 and 统计服务.
最终用户可以操作主题和组列表(添加或删除项目),并且我必须在每次更改后重新计算统计信息。在此应用程序中我使用Subjects and 订阅 from rx.js跟踪此类变化。
所以,在我的组件中我可以写这样的东西:
for 组组件
removeGroup() {
this.groupService.removeGroup(this.group);
this.statisticsService.updateStatistics();
}
for 主题组件
removeTheme() {
this.themeService.removeTheme(this.theme);
this.statisticsService.updateStatistics();
}
但从逻辑上讲,这些组件不必了解统计数据。当然我可以移动依赖统计服务 into 主题服务 and 集团服务,但随后我将不得不打电话统计服务.updateStatistics()在每一种改变主题或组集合的方法中。这就是为什么我想通过订阅来实现直接的跨服务通信。
最后是我的问题:
这是个好主意吗?
如果可以的话,最好的实施方式是什么?
当我使用订阅在组件中,我将其注册在ngOnInit()方法并取消订阅ngOnDestroy()以防止内存泄漏。
我可以在服务的构造函数中订阅它吗?我应该何时何地取消订阅?或者,当我在应用程序模块级别将我的服务注册为提供商时,也许没有必要?
StatisticsService
应订阅主题和群组列表。您的各个组件应该只订阅它们各自的服务(ThemeComponent 到 ThemeService、Group 到 Group 等)。
为了简单起见,我将只关注ThemeService
but GroupService
很相似。ThemeService
应该有一个内部Subject
当调用remove时,Subject
接下来将是一个值(可能是整个新列表)。
StatisticsService
将订阅ThemeService
变化后可观察并重新计算。它看起来像这样
/* theme.service.ts */
@Injectable()
export class ThemeService {
private _list$ = new Subject<ThemeList>();
get list(): Observable<ThemeList> {
return this._list$.asObservable();
}
set list(newList: ThemeList) {
this._list$.next(newList);
}
}
/* statistics.service.ts */
@Injectable()
export class StatisticsService {
private _calculation$ = new Subject<StatisticResult>();
constructor(private themeService: ThemeService) {
themeService.list.subscribe((themeList: ThemeList) => this.updateCalculation(themeList));
}
get calculation(): Observable<StatisticResult> {
return this._calculation$.asObservable();
}
updateCalculation(newData: ThemeList | GroupList) {
// ... do stuff
this._calculation.next(statisticResult);
}
}
/* statistics.component.ts */
@Component({
selector: 'statistics',
template: '<p>{{ statisticResult$ | async }}</p>'
})
export class StatisticsComponent {
statisticResult$: Observable<StatisticResult>;
constructor(private statisticsService: StatisticsService) {
this.statisticResult$ = statisticsService.calculation;
}
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)