So I try to use angular dependency injection in ngOnInit instead of constructor. I found some examples of this using a factory provider, but things does not quite work...
I get a reference to a
let myClassType: Type<MyClass> = ....
object that I can instantiate myself using
let myClassInstance = new myClassType(http)
but when I try to set up DI to allow me the same using DI I seem to fail... For some reason I get error messages in the console stating that myClassType on the return line of the myClassFactory function isn't a constructor, but since it's possible to manually create a instance using the same code elseware...
On my Component I use this constructor:
constructor(@Inject(MyClass) private _myClassFactory: (myClassType: Type<MyClass>) => MyClass
My understanding is that this pattern should be possible in components ngOnInit:
let myClassInstance: MyClass = this._myClassFactory(myClassType);
and my model has this:
@NgModule({
declarations: [
AppComponent
],
imports: [
BrowserModule,
HttpClientModule,
AppRoutingModule
],
providers: [
myClassProvider
],
bootstrap: [ AppComponent ]
})
and my MyClass.ts looks like this:
@Injectable()
export abstract class MyClass {
constructor(http: HttpClient) {}
}
export function myClassFactory(myClassType: Type<MyClass>, http: HttpClient): MyClass {
return new myClassType(http);
};
export let myClassProvider = {
provide: MyClass,
useFactory: myClassFactory,
deps: [HttpClient]
};
The reason I want to do this unusual pattern is because I want to be able to create an instance of MyClass using parameters passed from a http call, so they will not be available when the component is created. I have simplified my example as much as possible.