Create custom decorator in angular

4k Views Asked by At

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

1

There are 1 best solutions below

1
On

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