feat(core): add destroyService

This commit is contained in:
thomas
2022-12-22 11:32:46 +01:00
parent 1560245067
commit c3bcb8d3c0
3 changed files with 108 additions and 0 deletions

View File

@@ -1 +1,2 @@
export * from './lib/destroy-service.service';
export * from './lib/random-http-error.utils';

View File

@@ -0,0 +1,39 @@
import { ClassProvider, inject, Injectable, OnDestroy } from '@angular/core';
import { Observable, Subject } from 'rxjs';
function describeDestroyService() {
@Injectable()
class DestroyService extends Subject<void> implements OnDestroy {
ngOnDestroy(): void {
this.next();
this.complete();
}
}
function provideDestroyService(): ClassProvider {
return {
provide: DestroyService,
useClass: DestroyService,
};
}
function injectDestroyService(): Observable<void> {
const destroy$ = inject(DestroyService, { self: true, optional: true });
if (!destroy$) {
throw new Error(
'It seems that you forgot to provide DestroyService. Add "provideDestroyService()" to your declarable\'s providers.'
);
}
return destroy$.asObservable();
}
return {
provideDestroyService,
injectDestroyService,
};
}
export const { provideDestroyService, injectDestroyService } =
describeDestroyService();