Skip to content

Instantly share code, notes, and snippets.

@sanjeevsubedi
Created March 7, 2023 15:17
Show Gist options
  • Save sanjeevsubedi/43c2f7cfce6ea4c59293614c6d3dde5a to your computer and use it in GitHub Desktop.
Save sanjeevsubedi/43c2f7cfce6ea4c59293614c6d3dde5a to your computer and use it in GitHub Desktop.
Angular class decorator to auto unsubscribe from all subscriptions
/**
* Angular class decorator to auto unsubscribe from all subscriptions
*
*/
export function unsubscribe() {
return function (constructor: any) {
const originalDestroy = constructor.prototype.ngOnDestroy;
constructor.prototype.ngOnDestroy = function () {
for (let prop in this) {
const property = this[prop];
if (property && typeof property.unsubscribe === 'function') {
property.unsubscribe();
}
}
originalDestroy.apply(this, arguments);
};
};
}
/**
* How to use it?
*
* @unsubscribe()
* export class CustomersComponent implements OnInit {
* dataSubscription: Subscription = new Subscription();
* ........
* }
*
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment