为什么我的主题可观察订阅者在角度中多次调用?

ahs*_*san 2 rxjs typescript angular

在角度我有这样的服务

  private subject = new Subject<any>();
  private  vehicleSubject = new Subject<any>();

  sendData = (data: any) => this.subject.next({ data });

  sendVehicleData = (data: any) => this.vehicleSubject.next({ data });

  getData = (): Observable<any> => this.subject.asObservable();

  getVehicleData = (): Observable<any> => this.vehicleSubject.asObservable();
Run Code Online (Sandbox Code Playgroud)

现在我有sidebar(parent)这样的组件,tab view两个都primeng在我的sidebar.component.html

{{用户?.全名}}

服务与检查</h3> --> 检查工作</h3> -->

在我的sidebar.component.ts时间sidebar打开并且用户单击外部时,sidebar我将像这样将数据传递到我的子组件

  onSidebarOutside(e) {
   if (this.index === 0 && this.sideBarVisible && 
     !this.isCustomerCancelBtnClicked) {
     e.target.value = true;
     this.verifyCustomer = e;
  } else if(this.index === 1){
      console.log('in index 1');
      this.dataService.sendVehicleData(true);
  }
  if (this.isCustomerCancelBtnClicked) {
    this.isCustomerCancelBtnClicked = false;
   }
  }
Run Code Online (Sandbox Code Playgroud)

在我的内部vehicle-side-list.component,我有一个订阅者来ngOnInit获取这样的数据

ngOnInit() {
   this.dataService.getVehicleData().subscribe(obj => {
     console.log('in vehicle item subscruber', obj);
    });
}
Run Code Online (Sandbox Code Playgroud)

但问题是,我内部的订阅者vehicle-side-list.component多次拨打电话,我console.log('in vehicle item subscruber', obj);多次收到此日志。我不明白为什么它会多次调用。我只发送一次值,并通过从sidebar组件发送值来多次调用。

我的组件调用结构是这样的

sidebar
  -customer-component
    -appointment-component
  -vehicle-component
    -appointment-component
  -inspection-component
    -appointment-component
Run Code Online (Sandbox Code Playgroud)

我想将数据从 传递sidebarappointment-component

我在这里做错了什么?

Jas*_*ngh 5

看来您还没有取消订阅 ngDestroy 方法内的可观察对象。

每当您单击时,您都会添加新组件,该组件会向该可观察对象添加更多侦听器。只需取消订阅子组件 ngDestroy 中的可观察对象,它就应该可以工作。

您需要对子组件进行以下更改。创建一个私有属性并用它来取消订阅。

private destroy:Subject = new Subject();

ngOnInit() {
   this.dataService.getVehicleData().pipe(
     takeUntil(this.destroy)     // import takeUntil from rxjs/operators.
      ).subscribe(obj => {
     console.log('in vehicle item subscruber', obj);
    });
}

ngOnDestroy() {
  this.destroy.next();
}
Run Code Online (Sandbox Code Playgroud)

[帖子已编辑]