Skip to content

Instantly share code, notes, and snippets.

@alxhub
Created March 22, 2018 16:29
Show Gist options
  • Save alxhub/fe3de230f5e5e5fc800983a3799304ea to your computer and use it in GitHub Desktop.
Save alxhub/fe3de230f5e5e5fc800983a3799304ea to your computer and use it in GitHub Desktop.
@Injectable()
export class OnDestroyService implements OnDestroy {
onDestroy = new Set<OnDestroy>();
register(service: OnDestroy) {
this.onDestroy.add(service);
}
ngOnDestroy(): void {
this.onDestroy.forEach(svc => svc.ngOnDestroy());
}
}
@Injectable()
export class MyService implements OnDestroy {
ngOnDestroy(): void {
console.log('called!');
}
}
@NgModule({
providers: [
OnDestroyService,
{
provide: MyService,
useFactory: (onDestroy: OnDestroyService) => {
const svc = new MyService();
onDestroy.register(svc);
return svc;
},
deps: [OnDestroyService],
},
],
})
export class MyModule {}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment