Created
March 25, 2019 14:45
-
-
Save marc-x-andre/5d092efceb0ee2c5c0c6d793d2a3a79c to your computer and use it in GitHub Desktop.
Auto unsubscribe from every Rxjs subcription inside a component
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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); | |
} | |
}; | |
}; | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
@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