Currently, I am working on an Angular application where I have numerous Subjects, BehaviorSubjects, and ReplaySubjects as properties in various services. I am attempting to create a TypeScript decorator that can be added to some of these Subjects to enhance functionality when the .next function is called on them, specifically to manually trigger a global change detection.
@Injectable({
providedIn: 'root',
})
export class MyService extends HttpService {
@TriggerGlobalChangeDetection
public mySubject$: BehaviorSubject<boolean> = new BehaviorSubject<boolean>(false);
}
Here is the content of the decorator.ts:
// export function TriggerGlobalChangeDetection(): (Target: any, propertyKey: string) => {
// const origNext = Target.prototype.next;
// Target.prototype.next = function () {
// console.log('overriding next');
// origNext.apply(this);
// GlobalChangeDetectionService.detectChanges();
// };
// };
export function TriggerGlobalChangeDetection(
target?: any,
propertyName?: string,
descriptor?: PropertyDescriptor
) {
const origNext = target.prototype.next;
console.log('overriding next');
origNext.apply(this);
GlobalChangeDetectionService.detectChanges();
}
// export const TriggerGlobalChangeDetection = (Target: any, p: string): any => {
// return class extends Target {
// next = (value: any): void => {
// super.next(value);
// GlobalChangeDetectionService.detectChanges();
// };
// };
// };
I have tried different implementations of the decorator, but all have failed due to the exception thrown by Target.prototype.next
. It seems that Target
is of type HttpService
, which may be why I cannot access mySubject$
.
If anyone has suggestions on how to make this work, I would greatly appreciate it.
Best regards, Simon