angular - Angular订阅另一个组件中的变量更改
问题描述
我有一个包含 3 个组件和 1 个服务的应用程序:
- 应用程序组件。这包含我的导航栏等。在导航栏中有一个垫选择,您可以在其中选择客户。
- 订单.组件。列出当前选定客户的订单。
- 产品.组件。列出当前选定客户的产品。
- 客户服务。一些用于客户的函数,还带有当前选中客户的变量
期望状态:
- 当未选择客户并且用户导航到订单或产品时,不应调用 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();
}
});
}
该功能运行良好,但我意识到,由于我从不取消订阅,这完全搞砸了应用程序,因为它在导航时会创建大量订阅。我在订单中添加了取消订阅(请参见下面的代码段),但是当我四处导航时,我收到以下错误:ObjectUnsubscribedErrorImpl {message: 'object unsubscribed', name: 'ObjectUnsubscribedError'}
ngOnDestroy() {
this.customerService.customerObserver.unsubscribe();
}
我已经尝试阅读订阅了一段时间,但被卡住了如何继续..关于如何安排以达到所需状态的任何提示?
解决方案
您可以将数据从服务发送到组件观察者。
private customerSubject = new Subject<number>();
customerSelectedAction$ = this.customerSubject.asObservable();
products$ = this.customerSelectedAction$.pipe(
switchMap(customerId=>this.http.get<Product[]>(`${this.url}?customerId=${customerId}`))
.pipe(
tap(data => console.log(data)),
catchError(this.handleError)
));
orders$ = this.customerSelectedAction$.pipe(
switchMap(customerId=>this.http.get<Orders[]>(`${this.url}?customerId=${customerId}`))
.pipe(
tap(data => console.log(data)),
catchError(this.handleError)
));
selectedCustomerChanged(customer: Customer): void {
this.customerSubject.next(customer.id);
}
之后,您根据您是哪个组件订阅products$
或observables。orders$
并使用selectedCustomerChanged(customer: Customer)
导航栏的方法。
推荐阅读
- go - 遍历未知长度的切片
- swiftui - Apple Watch 上的 SwiftUI 全屏显示
- slack - 链接公共 Slack 频道时获取私人频道信息
- python - 为数百万数据实现的数据结构
- javascript - 无法让程序运行。(Javascript、HTML、CSS)
- sql - 我想在 BigQuery 中使用表达式的特定列上的最大列值对记录进行重复数据删除
- aspose - 保存 Aspose.Slides.Presentation 可防止文件被打开
- ruby-on-rails - 将 Rails 应用程序部署到 Heroku 时出现问题(无法加载此类文件 -- rake)
- php - 使用 PHP 通过 OTP SMS 验证手机号码
- android - 登录错误:登录此应用程序时出错。请稍后在 Flutter for android 模块中重试