0

I am trying to create custom decorators that returns a new instance of a class and this class must be created from an injected service which I can't figure out how to access it from the decorator function

Custom decorator

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

I want to access MainService from my custom decorator which I tried using the module but the injector property does not exist!

The service

@Injectable()
export class MainService {

  config;

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

Expected Usage

export class AppComponent implements OnInit {

  @Collection('posts') postsCollection;


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

Update

Here is a stackblitz reproduction

Murhaf Sousli
  • 11,806
  • 20
  • 109
  • 179

1 Answers1

0

The value you return from a field decorator will not be used as the value for the field as you asume.

You can change the field to a property in the decorator by returning a property descriptor which will do the call to get the value of the property.

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
  };
}
Titian Cernicova-Dragomir
  • 196,102
  • 20
  • 333
  • 303
  • 1
    I tried this, I am getting `Property 'injector' does not exist on type 'typeof CollectionModule'.` on `CollectionModule.injector` – Murhaf Sousli Sep 19 '18 at 15:56