无法取消订阅ngOnDestroy()Angular 5

时间:2017-12-13 14:58:42

标签: angular components observable unsubscribe

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

基础测试:

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

1 个答案:

答案 0 :(得分:0)

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

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