Skip to content

Instantly share code, notes, and snippets.

@marcellkiss
Last active June 29, 2022 15:52
Show Gist options
  • Save marcellkiss/9d2fa37fce7b67228023e00abc9e0690 to your computer and use it in GitHub Desktop.
Save marcellkiss/9d2fa37fce7b67228023e00abc9e0690 to your computer and use it in GitHub Desktop.
Typescript decorator example for unsubscribe
import { Component, EventEmitter, Input, Output } from '@angular/core';
import { ProductDto } from '@ev-customer-portal/frontend/api-client';
import { interval, Subject, takeUntil } from 'rxjs';
@AddDestroy$()
@Component({...})
export class RequestAccessDialogComponent {
public sub = interval(1000)
.pipe(untilDestroy$(this))
.subscribe((v) => {
console.log(`interval is ticking`, v);
});
}
export function AddDestroy$(): ClassDecorator {
return (componentClass: any) => {
const ngOnDestroy = componentClass.prototype.ngOnDestroy;
componentClass.prototype.destroy$ = new Subject<void>();
componentClass.prototype.ngOnDestroy = function (this: any) {
ngOnDestroy && ngOnDestroy.call(this);
componentClass.prototype.destroy$.next();
};
};
}
export function untilDestroy$(component: any) {
return takeUntil(component.destroy$);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment