I have a parent class where I want to inject some modules, then I have some derived classes where I would like to use these injected modules.
However in the derived class you have to call super()
without parameters, so injected modules in parent class are undefined.
How could this be done?
import {inject} from 'aurelia-framework';
import {HttpClient} from 'aurelia-http-client';
@inject (HttpClient)
export class Parent{
constructor(module){
//this constructor is called from derived class without parameters,
//so 'module' is undefined !!
this.injectedmodule = module;
}
}
export class ClassA extends Parent{
constructor(){
super();
this.injectedmodule.get() // injectedmodule is null !!!
}
}
Well, just found the solution, module is actually injected in derived class and passed to parent through super() call:
import {inject} from 'aurelia-framework';
import {HttpClient} from 'aurelia-http-client';
@inject (HttpClient)
export class Parent{
constructor(module){
this.injectedmodule = module;
}
}
export class ClassA extends Parent{
constructor(module){
super(module);
this.injectedmodule.get() // ok !!!
}
}
The general recommendation is to avoid inheritance if at all possible. Utilize composition instead. In this instance:
import {inject} from 'aurelia-framework';
import {HttpClient} from 'aurelia-http-client';
@inject (HttpClient)
export class Parent{
constructor(module){
this.injectedmodule = module;
}
}
@inject(Parent)
export class ClassA {
constructor(parent){
this.parent = parent;
this.parent.injectedmodule.get() // ok !!!
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With