首页 > 解决方案 > Angular订阅另一个组件中的变量更改

问题描述

我有一个包含 3 个组件和 1 个服务的应用程序:

期望状态:

当前状态

  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();
  }

我已经尝试阅读订阅了一段时间,但被卡住了如何继续..关于如何安排以达到所需状态的任何提示?

标签: angularrxjssubscribe

解决方案


您可以将数据从服务发送到组件观察者。

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)导航栏的方法。


推荐阅读