取消订阅不在NgOnDestroy上工作

时间:2018-05-02 09:44:49

标签: angular angular2-observables behaviorsubject

这是我获得BehaviorSubject

的服务中的代码
  private messageSource = new BehaviorSubject<Customer>(getEmptyCustomer());
  public currentMessage = this.messageSource.asObservable();

这是方法

  public passCustomer(data: Customer) {
    this.messageSource.next(data);
  }

在我使用passCustomer

的组件中
  public passDataToNewContract(customer: Customer) {
    this.customerService.passCustomer(customer);
    this.router.navigate(['/dashboard/nuoviClienti/aggiungiCliente']);
  }

实际上我想将数据传递给兄弟组件并且它有效。 但是当我试图取消订阅

时会出现问题
  public ngOnInit() {
    this.alive = this.customerService.currentMessage.subscribe((message) => {
      console.log(message);
    });
  }

  public ngOnDestroy() {
    this.alive.unsubscribe();
  }

它不起作用。我尝试更改激活的ngOnDestroy组件,但每次都会打印数据。 我也用takeUntil尝试了这个方法,但没有。

1 个答案:

答案 0 :(得分:0)

我认为以前的订阅仍然保留该流,因此您需要在销毁组件之前清除它。关闭标签页后,终止订阅。一种方法是:

someSubscription: Subscription
ngOnInit() {
      this.customerService.passCustomer();
      this.someSubscription = this.customerService.currentMessage.subscribe(data => {
      console.log(data)
    });
}


ngOnDestroy() {
    if (this.someSubscription) {
        this.someSubscription .unsubscribe();
    }
}

或其他类似方式

 destroy$ = new Subject();

 ngOnInit() {
      let empty = [];
      this.customerService.passCustomer(empty);
      this.customerService.currentDeviceList
       .pipe(takeUntil(this.destroy$)) // takUntil from rxjs
       .subscribe(data => {
           if(data.length !=0){
             console.log(data)
           }    
    });
  }

 ngOnDestroy(){
    this.destroy$.next();
    this.destroy$.complete(); // always call complete for guaranteed subscription removal
 }
相关问题