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

时间:2018-06-13 11:32:23

标签: angular rxjs observable unsubscribe

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

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

这给了我这个错误:

财产&#39;取消订阅&#39;类型&#39; Observable&#39;中不存在。你是说&#39;订阅&#39;?

2 个答案:

答案 0 :(得分:1)

您只能在unsubscribe上使用Subscription。您正试图在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();
}

答案 1 :(得分:0)

出于某种原因,在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();
}
相关问题