How to introduce parent class in Aurelia?

I have a parent class where I want to insert some modules, then I have derived classes where I would like to use these modules with injections. However, in the derived class, you need to call super() without parameters, so the modules you entered in the parent class are undefined. How can I do that?

 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 !!! } } 
+6
source share
3 answers

Well, I just found a solution, the module is actually introduced into the derived class and passed to the parent object via the 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 !!! } } 
+8
source

A general recommendation is to avoid inheritance, if at all possible. Use composition instead. In this case:

 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 !!! } } 
+6
source

There is a website there that explains to me a great way to do this https://ilikekillnerds.com/2016/11/injection-inheritance-aurelia/

Here is an example:

 import {inject} from 'aurelia-framework'; import {Router} from 'aurelia-router'; @inject(Router) export class Parent { constructor(router) { this.router = router; } } import {Parent} from './parent'; export class Child extends Parent { constructor(...rest) { super(...rest); } } 
+1
source

Source: https://habr.com/ru/post/986709/


All Articles