Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/angular/33.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Angular 角形装饰器don';t在这个范围内工作_Angular_Typescript_Decorator - Fatal编程技术网

Angular 角形装饰器don';t在这个范围内工作

Angular 角形装饰器don';t在这个范围内工作,angular,typescript,decorator,Angular,Typescript,Decorator,使用自定义装饰器,我希望将一个属性和另一个方法一起注入到一个方法中。装饰师: function test() { return function(target, key, descriptor) { const originalMethod = descriptor.value; descriptor.value = function(...args: any[]) { Object.defineProperty(this, "foo", {

使用自定义装饰器,我希望将一个属性和另一个方法一起注入到一个方法中。装饰师:

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!
  }
}
但这不起作用(错误:this.bar.foo不是函数):


我做错了什么?

调用
关键字引用AppComponent实例时,在
栏中
函数。当您调用
bar
方法时,应该向AppComponent添加
foo
元素

如果您仍然希望像
(this.bar as any).foo()一样访问它然后在
栏上定义foo字段,而不是

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;
  };
}
@test()
bar() {
    (this.bar as any).foo(); // Error: this.bar.foo is not a function
}
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;
  };
}