【问题标题】:Pass aditional arguments to method decorator inside angular component将附加参数传递给角度组件内的方法装饰器
【发布时间】:2019-08-22 16:49:23
【问题描述】:

假设我们有很多方法要在原始方法中添加确认对话框。因此我们决定构建一个自定义装饰器。

@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;
  };
}

但这种方法不起作用,因为

无法读取未定义 (hero.component.ts) 的属性“对话框”

如何将附加参数传递给装饰器?我已经考虑将dialog 传递给原始函数本身以通过args 访问它,但这对我来说听起来像是一个非常肮脏的黑客攻击?

提前致谢!

【问题讨论】:

    标签: angular typescript decorator angular-decorator


    【解决方案1】:

    您无法访问装饰器参数中的实例字段。装饰器应用于类而不是实例。

    简单的解决方案是传入对话字段的名称,但这意味着该字段需要公开。

    您还需要更改转发参数和this 的方式。由于我们需要访问实际传入的 this 我们不能使用箭头函数,我们需要使用 apply 来转发 this

    class HeroComponent {
      constructor(public dialog: MatDialog) { }
    
      @confirmByDialog("dialog") // Checked by the compiler.
      deleteHero() { }
    }
    function confirmByDialog<K extends string>(dialog: K) {
      return (target: Record<K, MatDialog>, key: string, descriptor: any) => {
        const originalMethod: Function = descriptor.value;
    
        descriptor.value = function (this: Record<K, MatDialog>, ...args: any[]) {
          const dialogRef = this[dialog].open(ConfirmationDialogComponent);
          return dialogRef
            .afterClosed()
            .subscribe((confirmed: boolean) => {
              if (confirmed) {
                originalMethod.apply(this, ...args);
              }
            });
        };
        return descriptor;
      };
    }
    

    【讨论】:

      猜你喜欢
      • 2013-03-10
      • 2018-06-07
      • 1970-01-01
      • 2014-11-17
      • 2015-03-23
      • 1970-01-01
      • 2021-11-21
      • 2018-08-24
      • 2014-10-01
      相关资源
      最近更新 更多