【发布时间】:2021-11-25 13:28:18
【问题描述】:
我有一个包含 3 个组件和 1 个服务的应用程序:
- 应用程序组件。这包含我的导航栏等。在导航栏中有一个垫选择,您可以在其中选择客户。
- orders.component。列出当前选定客户的订单。
- products.component。列出当前选定客户的产品。
- 客户服务。一些用于客户的函数,也是与当前选择的客户相关的变量
所需状态:
- 当未选择客户且用户导航至订单或产品时,不应调用 API。
- 当用户在订单/产品页面上时在导航栏中选择客户时,API 应触发以获取所选客户的订单/产品。
- 客户变更时,应触发 API 加载新客户订单/产品
- 当客户被选中并且用户导航到订单/产品时,应该直接调用 API 来获取数据
当前状态
- 目前我已将
customerObserver: Subject<boolean> = new Subject<boolean>();添加到customer.service。 - 在导航栏(app.components)中选择客户时,它会调用customer.service中的一个函数,该函数最终将执行
this.customerObserver.next(this.customer); - 在订单和产品组件中,我都这样做:
ngOnInit(): void {
if (this.customerService.customer) {
this.loadOrders();
}
this.customerService.customerObserver.subscribe(customer => {
if(customer) {
this.loadOrders();
}
});
}
该功能运行良好,但我意识到,由于我从不取消订阅,这完全搞砸了应用程序,因为它在导航时会创建大量订阅。我在订单中添加了取消订阅(请参阅下面的 sn-p),但是当我四处导航时,我收到以下错误:ObjectUnsubscribedErrorImpl {message: 'object unsubscribed', name: 'ObjectUnsubscribedError'}
ngOnDestroy() {
this.customerService.customerObserver.unsubscribe();
}
我已经尝试阅读订阅了一段时间,但卡住了如何继续。关于如何安排以达到所需状态的任何提示?
【问题讨论】: