如何在Aurelia的父类中注入?

时间:2015-05-07 07:27:54

标签: javascript inheritance inject aurelia ecmascript-7

我有一个父类,我想要注入一些模块,然后我有一些派生类,我想使用这些注入的模块。 但是在派生类中,您必须在没有参数的情况下调用super(),因此未在父类中注入模块。 怎么可以这样做?

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 !!!   
    }
}

3 个答案:

答案 0 :(得分:8)

好吧,刚刚找到解决方案,模块实际上是在派生类中注入的,并通过super()调用传递给父级:

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 !!!   
    }
}

答案 1 :(得分:6)

一般建议尽可能避免继承。而是利用构图。在这种情况下:

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 !!!   
    }
}

答案 2 :(得分:1)

这是一个网站,为我解释一个美丽的方式来做到这一点 https://ilikekillnerds.com/2016/11/injection-inheritance-aurelia/

以下是例子:

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);
    }
}