busy.decorator.ts (1227B)
1 import { finalize, Observable, tap } from 'rxjs'; 2 import { BusyService } from './busy.service'; 3 import { inject } from '@angular/core'; 4 5 export interface BusyOptions { 6 message?: string; 7 showBusy?: boolean; 8 } 9 10 export function Busy(options: BusyOptions = { showBusy: true }): MethodDecorator { 11 return function ( 12 target: any, 13 propertyKey: string | symbol, 14 descriptor: PropertyDescriptor 15 ) { 16 // Store the original method implementation 17 const originalMethod = descriptor.value; 18 19 // Replace the original method with a new function 20 descriptor.value = function (this: any, ...args: any[]): Observable<any> { 21 const busyService = BusyService.Instance; 22 const { message = 'Loading...', showBusy = true } = options; 23 24 // Call the original method to get the Observable 25 const result: Observable<any> = originalMethod.apply(this, args); 26 27 // If showBusy is false, return the original observable 28 if (!showBusy) { 29 return result; 30 } 31 32 // Wrap with busy indicator 33 return result.pipe( 34 tap(() => busyService.show(message)), 35 finalize(() => busyService.hide()) 36 ); 37 }; 38 39 return descriptor; // Return the modified descriptor 40 }; 41 }