1

I have created a custom decorator for class methods and it depends upon injected services of the class of the decorated method. The injectables that this decorator relies upon are userService and authService.

Here is the decorator:


export function authenticated(target: Object, propertyKey: string, descriptor: TypedPropertyDescriptor) {
    let originalMethod = descriptor.value;

    descriptor.value = function(...args: any[]) {
        if (!this.userService || !this.authService) {
            throw Error("Class must import userService and authService");
        }

        if (!this.userService.isAuthenticated$.value) {
            return this.authService.openLoginSignup();
        }

        return originalMethod.apply(this, args);
    };

}

I implemented a check to confirm that the services are imported into the parent class correctly, but the problem with it is that it only gets called when the decorated method gets called.

Is there any way to inject angular 2 injectables into decorators or other non-components?

Derek
  • 560
  • 6
  • 19
  • I guess the answer is no. You can get root injector in decorator with [some hack](https://stackoverflow.com/questions/39409328/storing-injector-instance-for-use-in-components) but not own component's injector. And certainly not parent injector for non-component class. Why not just force `authService`, etc. properties with class interface? This is what interfaces are for, to prevent errors at design time. – Estus Flask Sep 14 '16 at 02:05
  • I was thinking about doing that initially, but was put off because interfaces can't describe private methods. However it is nice that I can remove the manual check from the decorator. There will always be trade-offs! Thanks for commenting. – Derek Sep 14 '16 at 02:56
  • Had the same case with privates recently, making them publics was the lesser evil. Privates can also be forced via parent abstract class with annotated constructor (though it will need `super` boilerplate if child constructor differs). – Estus Flask Sep 14 '16 at 03:27

0 Answers0