6

我有一个父类,我想在其中注入一些模块,然后我有一些派生类,我想在其中使用这些注入的模块。但是在派生类中,您必须在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 !!!   
    }
}
4

3 回答 3

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 !!!   
    }
}
于 2015-05-07T07:51:36.317 回答
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 !!!   
    }
}
于 2015-05-07T12:14:57.720 回答
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);
    }
}
于 2017-09-21T08:09:24.187 回答