【问题标题】:Unable to unsubscribe in ngOnDestroy() Angular 5无法在 ngOnDestroy() Angular 5 中取消订阅
【发布时间】:2018-05-27 12:34:12
【问题描述】:

我无法取消订阅我的测试。 还有人有这个问题吗?? (我做错什么了吗?)

基本测试:

describe('ngOnDestroy()', () => {
  it('should unsubscribe if isLoggedInSub is defined', async(() => {
    comp.ngOnInit();
    fixture.detectChanges();
    comp.ngOnDestroy();
    fixture.detectChanges();
    expect(comp.isLoggedInSub).not.toBeDefined();
  }));
});

控制台错误:

Uncaught Expected Subscriber({ closed: true, _parent: null, _parents: null, _subscriptions: null, syncErrorValue: null, syncErrorThrown: false, syncErrorThrowable: false, isStopped: true, destination: SafeSubscriber({ closed: false, _parent: null, _parents: null, _subscriptions: null, syncErrorValue: null, syncErrorThrown: false, syncErrorThrowable: false, isStopped: false, destination: Object({ closed: true, next: Function, error: Function, complete: Function }), _parentSubscriber: <circular reference: Object>, _context: <circular reference: Object>, _next: Function, _error: undefined, _complete: undefined }) }) not to be defined.
at Object.testing_3.async

【问题讨论】:

  • 你是如何创建isLoggedInSub的?你的ngOnDestroy 方法是什么样的?
  • isLoggedInSub: Subscription; isLoggedInSub = someObservableFunction.subscribe(() =&gt; {}); ngOnDestroy() { isLoggedInSub.unsubscribe() }

标签: angular components observable unsubscribe


【解决方案1】:

如果您有一个主题并且您直接尝试以上述任何方法取消订阅,那么我们将面临此类错误。 示例:

//AppComponent.ts

export class AppComponent implements OnDestroy{
 appSubject:new Subject();
 appSubject.subscribe(()=>...)
 ngOnDestroy() {
   appSubject.unsubscribe(); // If your subject is passing the next value from a 
                         different component
 }
}

这通常会导致此错误,因为另一个组件引用了主题。

更好的方法是

export class AppComponent implements OnDestroy{
 appSubject:new Subject();
 $subjectSubscription:Subscription = appSubject.subscribe(()=>...)
 ngOnDestroy() {
   $subjectSubscription.unsubscribe();
 }
}

【讨论】:

  • 谢谢。这是我已经在做的,但取消订阅仍然不起作用。
  • 好的,您能否分享一个您要取消订阅的规范文件的 plunker,以便我们提供帮助。
猜你喜欢
  • 2021-07-22
  • 2018-08-31
  • 2016-04-27
  • 2018-11-22
  • 2019-02-04
  • 1970-01-01
  • 2023-01-04
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多