Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to inject in a parent class in Aurelia?

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 !!!   
    }
}
like image 945
Alex Garcia Avatar asked May 07 '15 07:05

Alex Garcia


2 Answers

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 !!!   
    }
}
like image 199
Alex Garcia Avatar answered Oct 08 '22 03:10

Alex Garcia


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 !!!   
    }
}
like image 30
Ashley Grant Avatar answered Oct 08 '22 01:10

Ashley Grant