【问题标题】:Angular decorator don't works on this scopeAngular 装饰器不适用于此范围
【发布时间】:2021-07-05 04:07:09
【问题描述】:

使用自定义装饰器,我想将一个带有另一个方法的属性注入一个方法。装饰者:

function test() {
  return function(target, key, descriptor) {
    const originalMethod = descriptor.value;
    descriptor.value = function(...args: any[]) {
      Object.defineProperty(this, "foo", {
        value: () => console.log("foo fired!"),
        enumerable: false,
        writable: false
      });
      return originalMethod.apply(this, args);
    };
    return descriptor;
  };
}

用法:

import { Component} from "@angular/core";

@Component({
  selector: "my-app",
  template: `<button (click)="bar()">Test</button>`,
})
export class AppComponent {

  @test()
  bar() {
    console.log("bar fired!");

    const self = this;
    (self as any).foo(); // this works!

    (this.bar as any).foo(); // this doesn't works!
  }
}

在线查看https://stackblitz.com/edit/angular-ivy-dhfasr?file=src%2Fapp%2Fapp.component.ts

我不明白,因为这行得通:

@test()
bar() {
    const self = this;
    (self as any).foo();
}

但这不起作用(错误:this.bar.foo 不是函数):

@test()
bar() {
    (this.bar as any).foo(); // Error: this.bar.foo is not a function
}

我做错了什么?

【问题讨论】:

    标签: angular typescript decorator


    【解决方案1】:

    bar 函数内部,当您调用它时,this 关键字引用 AppComponent 实例。当您调用bar 方法时,预计您在AppComponent 中添加了foo 元素。

    如果您仍想像 (this.bar as any).foo(); 那样访问它,那么在 bar 上定义 foo 字段,而不是 this

    function test() {
      return function(target, key, descriptor) {
        const originalMethod = descriptor.value; // no point of overriding it. we just add a field
        Object.defineProperty(originalMethod, "foo", {
          value: () => console.log("foo fired!"),
          enumerable: false,
          writable: false
        });
        return descriptor;
      };
    }
    

    【讨论】:

      猜你喜欢
      • 2019-03-03
      • 1970-01-01
      • 1970-01-01
      • 2018-12-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-08-15
      • 2016-06-30
      相关资源
      最近更新 更多