Skip to content

Instantly share code, notes, and snippets.

@marc-x-andre
Created March 25, 2019 14:45
Show Gist options
  • Save marc-x-andre/5d092efceb0ee2c5c0c6d793d2a3a79c to your computer and use it in GitHub Desktop.
Save marc-x-andre/5d092efceb0ee2c5c0c6d793d2a3a79c to your computer and use it in GitHub Desktop.
Auto unsubscribe from every Rxjs subcription inside a component
export function AutoOnDestroy(blackList = []) {
return function (constructor: any) {
const original = constructor.prototype.ngOnDestroy;
constructor.prototype.ngOnDestroy = function () {
for (const prop in this) {
if (this.hasOwnProperty(prop)) {
const property = this[prop];
if (!blackList.includes(prop)) {
if (property && (typeof property.unsubscribe === 'function')) {
property.unsubscribe();
}
}
}
}
if (original && typeof original === 'function') {
original.apply(this, arguments);
}
};
};
}
@Component({
selector: 'app-test',
templateUrl: './test.component.html',
styleUrls: ['./test.component.scss']
})
@AutoOnDestroy()
export class TestComponent implements OnInit {
private sub: Subscription;
...
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment