0.0.3 • Published 5 years ago

take-until-ng-destroy v0.0.3

Weekly downloads
3
License
MIT
Repository
github
Last release
5 years ago

take-until-ng-destroy

Unsubscribe subscriptions when the component or service is destroyed

Features

  1. Type checking to make sure the interface ngOnDestroy is implemented
  2. Using observable pipe function to unsubscribe
  3. Using observable prototype method to unsubscribe

Installation

npm install take-until-ng-destroy --save


Usage

Using observable pipe function

  • import pipe function 'takeUntilNgDestroy'
import { takeUntilNgDestroy } from 'take-until-ng-destroy';
  • use 'takeUntilNgDestroy' in Observable.pipe() method. Real time type checking to make sure the interface ngOnDestroy is implemented in the component or service.
@Component({
    ....
})
export class Page1Component implements OnDestroy {

  constructor() { }

  ngOnInit() {
    interval(1000)
      .pipe(takeUntilNgDestroy(this))
      .subscribe({
        next(val) { console.log('page1 - ', val); },
        complete() { console.log('page1 - destroyed'); }
      });
  }

  ngOnDestroy() {}
}

Using observable prototype method

  • Add the following codes to the main code, such as main.ts
// import function ngDestroySubscription
import { ngDestroySubscription } from 'take-until-ng-destroy';
// Declare and add the prototype method 'takeUntilNgDestroy' to Observable
declare module 'rxjs/internal/Observable' {
  interface Observable<T> {
    takeUntilNgDestroy: typeof ngDestroySubscription;
  }
}

Observable.prototype.takeUntilNgDestroy = ngDestroySubscription;
  • Use Observable method takeUntilNgDestroy directly. Real time type checking to make sure the interface ngOnDestroy is implemented in the component or service.
@Component({
  ...
})
export class Page2Component implements OnDestroy {

  constructor() { }

  ngOnInit() {
    interval(1000)
      .takeUntilNgDestroy(this)
      .subscribe({
        next(val) { console.log('page2 - ', val); },
        complete() { console.log('page2 - destroyed'); }
      });
  }

  ngOnDestroy() {}
}

License

MIT

0.0.3

5 years ago

0.0.2

5 years ago

0.0.1

5 years ago