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

Observable, unsubscribe in ngOnDestroy not working

我有一个打开的对话框,其中包含一个组件...在该组件中我进行了订阅。关闭时我想取消订阅..

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

这给了我这个错误:

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

您只能在 Subscription 上使用 unsubscribe。您正在尝试在 Observable.

上使用它

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

但是,如果您在 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();
}

出于某种原因,在 ngOnDestroy 中取消订阅破坏了应用程序...我就是这样解决的:

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


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

public closeSearch() {
 this.onClose.apply();
 this.breakpointObserverSubscription.unsubscribe();
}