如何退订观察员?

时间:2019-08-22 13:16:27

标签: angular angular7 angular8

有观察者:

export class ListenerService {

    private action: Subject<IActionData> = new Subject();

    apply(data?: IActionData) {
        this.action.next(data);
    }

    changes(): Observable<any> {
        return this.action.asObservable();
    }
}

使用方式是

this.sub = this.listener.changes();
this.sub.subscribe((res: IActionData) => {});

在销毁组件中,我试图取消设置this.sub

 ngOnDestroy() {
    if (this.sub) {
      console.log(this.sub);
      this.sub.unsubsribe();
    }
  }

它说:

  

错误TypeError:this.sub.unsubsribe不是函数       在VersionsAddressComponent.ngOnDestroy

4 个答案:

答案 0 :(得分:2)

之类的组件中的

订阅值

sub: Subscription;

您的订阅将是

this.sub = this.listner.changes.subscribe((res: IActionData) => {});

然后onDestroy将

ngOnDestroy() {
   this.sub.unsubsribe();
 }

答案 1 :(得分:1)

那应该做的:

this.sub = this.listener.changes().subscribe((res: IActionData) => {});
this.sub.unsubsribe();

答案 2 :(得分:1)

您必须使用RXJS订阅:

  subscription = new Subscription() ; 
this.subscription.add(this.listener.changes().subscribe((res: IActionData) => {}));



  ngOnDestroy(): void {
    this.subscription.unsubscribe();
  }

答案 3 :(得分:0)

Observable不能退订,subscription可以退订:

例如:

this.sub = this.listener.changes().subscribe((res: IActionData) => {});

然后您可以按照完成的方式取消订阅:

ngOnDestroy() {
   this.sub.unsubsribe();
}