可观察,取消订阅 ngOnDestroy 不起作用

Mac*_*ito 1 unsubscribe observable rxjs angular

我有一个对话框打开并包含一个组件...在我订阅的组件中。关闭时我想退订..

private deviceObserver: Observable<BreakpointState> = this.breakpointObserver.observe([Breakpoints.XSmall]);

this.deviceObserver.subscribe(result => {
  if (result.matches) {
    this.deviceType = 'mobile';
  } else {
    this.deviceType = 'desktop';
  }
});

ngOnDestroy() {
 this.deviceObserver.unsubscribe();
}
Run Code Online (Sandbox Code Playgroud)

这给了我这个错误:

'Observable' 类型不存在属性 'unsubscribe'。您指的是 'subscribe' 吗?

Pie*_*Duc 5

您只能unsubscribeSubscription. 您正在尝试在Observable.

如果您使用async管道在组件内使用 observable ,则无需取消订阅。这是由框架自动完成的。

但是,如果您在 . 中使用它component.ts,那么一种方法是这样做。还有其他选项,takeUntil例如使用管道:

private deviceObserver: Observable<BreakpointState> = 
                        this.breakpointObserver.observe([Breakpoints.XSmall]);

ngOnInit() {
  this.sub = this.deviceObserver.subscribe(result => {
    if (result.matches) {
      this.deviceType = 'mobile';
    } else {
      this.deviceType = 'desktop';
    }
  });
}

ngOnDestroy() {
 this.sub.unsubscribe();
}
Run Code Online (Sandbox Code Playgroud)