https://github.com/samcodex/take-until-ng-destroy
https://github.com/samcodex/take-until-ng-destroy
Last synced: about 1 month ago
JSON representation
- Host: GitHub
- URL: https://github.com/samcodex/take-until-ng-destroy
- Owner: samcodex
- Created: 2019-04-08T04:58:36.000Z (about 7 years ago)
- Default Branch: master
- Last Pushed: 2019-04-11T19:27:16.000Z (about 7 years ago)
- Last Synced: 2025-10-24T18:58:01.775Z (8 months ago)
- Language: TypeScript
- Size: 136 KB
- Stars: 0
- Watchers: 1
- Forks: 0
- Open Issues: 0
-
Metadata Files:
- Readme: README.md
Awesome Lists containing this project
README
# 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 {
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