Imagine a scenario where there are multiple methods requiring the addition of a confirmation dialog. In order to streamline this process, a custom decorator is created.
@Component({...})
export class HeroComponent {
constructor(private dialog: MatDialog) {}
@confirmByDialog(this.dialog)
deleteHero() { ... }
}
export function confirmByDialog (dialog: MatDialog): MethodDecorator {
return (target: Function, key: string, descriptor: any) => {
const originalMethod = descriptor.value;
descriptor.value = (...args: any[]) => {
const dialogRef = dialog.open(ConfirmationDialogComponent);
return dialogRef
.afterClosed()
.subscribe((confirmed: boolean) => {
if (confirmed) {
originalMethod();
}
});
};
return descriptor;
};
}
However, an issue arises with the code:
Cannot read property 'dialog' of undefined (hero.component.ts)
The question now stands: How can additional parameters be passed to a decorator? One potential solution could involve passing the `dialog` parameter directly to the original function and accessing it through the `args`, but this approach may seem like a less than ideal workaround.
We appreciate any insights or suggestions on this matter!