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

私にとって、それを行うための美しい方法を説明するWebサイトがあり ます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 に答える