I've been working on creating custom decorators that can return a new instance of a class. The catch is that this class needs to be created from an injected service, and I'm struggling 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've been trying to get hold of the MainService
from my custom decorator using the module, but the injector
property seems to be missing!
The Service
@Injectable()
export class MainService {
config;
getCollection(endpoint: string): Collection {
return new Collection(endpoint, this.config);
}
}
Example Usage
export class AppComponent implements OnInit {
@Collection('posts') postsCollection;
ngOnInit() {
console.log(this.postsCollection);
}
}
Update
Check out this Stackblitz reproduction