mirror of
https://github.com/Raghu-Ch/angular-challenges.git
synced 2026-02-10 21:03:03 -05:00
feat(core): add destroyService
This commit is contained in:
@@ -1 +1,2 @@
|
||||
export * from './lib/destroy-service.service';
|
||||
export * from './lib/random-http-error.utils';
|
||||
|
||||
39
libs/shared/utils/src/lib/destroy-service.service.ts
Normal file
39
libs/shared/utils/src/lib/destroy-service.service.ts
Normal 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();
|
||||
Reference in New Issue
Block a user