【问题标题】:Create custom decorator in angular以角度创建自定义装饰器
【发布时间】:2018-09-19 13:11:50
【问题描述】:

我正在尝试创建自定义装饰器,它返回一个类的新实例,并且这个类必须从一个注入的服务创建,我不知道如何从装饰器函数访问它

自定义装饰器

export function Collection(endpoint: string) {
  return function (constructor: any) {
    const mainService = CollectionModule.injector.get(MainService);
    return mainService.getCollection(endpoint);
  };
}

我想从我尝试使用模块但injector 属性不存在的自定义装饰器中访问MainService

服务

@Injectable()
export class MainService {

  config;

  getCollection(endpoint: string): Collection {
    return new Collection(endpoint, this.config);
  }
}

预期用途

export class AppComponent implements OnInit {

  @Collection('posts') postsCollection;


  ngOnInit() {
     console.log(this.postsCollection);
  }
}

更新

这是stackblitz reproduction

【问题讨论】:

标签: angular typescript angular-decorator


【解决方案1】:

您从字段装饰器返回的值不会像您假设的那样用作该字段的值。

您可以通过返回属性描述符将字段更改为装饰器中的属性,该属性描述符将调用以获取属性的值。

export function Collection(endpoint: string) {
  return function (constructor: Object, propertyName: string) {
    let descriptor: PropertyDescriptor = {
      get(this: any){
        const mainService = this["_" + propertyName] || (this["_" + propertyName] =  CollectionModule.injector.get(MainService);
        return mainService
      }
    }
    return descriptor
  };
}

【讨论】:

  • 我试过了,我在CollectionModule.injector上得到Property 'injector' does not exist on type 'typeof CollectionModule'.
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2020-06-02
  • 2015-04-17
  • 1970-01-01
  • 2013-02-06
  • 2015-03-04
  • 2019-07-20
相关资源
最近更新 更多