Is it possible to use dependency injection within mixing in typescript/angular?
What I have:
export const MyMixin = <T extends Type<MyClass>>(Base: T): T =>
class extends Base {
constructor(...args: any[]) {
super(...args);
}
};
Now I want to add the method myMethod(), which uses a Service. I try this:
export const MyMixin = <T extends Type<MyClass>>(Base: T): T =>
class extends Base {
constructor(injector: Injector, ...args: any[]) { // ???? throws ts-error (2545)
super(...args);
this.myMethod();
}
private myMethod(): void {
this.injector(SomeService).doSomething();
};
};
Typescript doesn’t like my new constructor. It throws:
A mixin class must have a constructor with a single rest parameter of type ‘any[]’.ts
(2545)
A similar question was asked 4 years ago: why do typescript mixins require a constructor with a single rest parameter any[]?
Muhammed Albarmavi served a solution (/a/56749960) which basically defines a global class with static methods, which serves the Injector. It works, but it feels like a anti-pattern.
Is there a solution, where I can use “clean” dependency injection on mixins?