简体   繁体   中英

How to unsubscribe from not initialized subscription in Angular

I got following error:

ERROR Error: Uncaught (in promise): TypeError: Cannot read property 'unsubscribe' of undefined

I have subscription not on ngOnInit and that's why I got this error, because my property that holding the subscription is not yet initialized, but what's the 'proper way' in such a situation.

Here is my code:

img

You can use takeUntil() operator of rxjs with pipe() before subscribing to the observable.

 unsubscribeSignal: Subject<void> = new Subject();

 ngOnInit() {
    this.subscription = this.observableToSubscribe
    .pipe(
       takeUntil(this.unsubscribeSignal.asObservable()),
    )
    .subscribe(result => {

      //Do some fancy stuff here

      console.log(result );
    });
  }

  ngOnDestroy(){
    this.unsubscribeSignal.next();
  }

Another benefit of using takeUntil instead of manually unsubscribing the subscription is that you can use a single Subject to unsubscribe multiple subscriptions at once.

You can check out my another answer here

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM