【问题标题】:How to inject in a parent class in Aurelia?如何在 Aurelia 中注入父类?
【发布时间】:2015-07-17 15:19:03
【问题描述】:

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

【问题讨论】:

    标签: javascript inheritance inject aurelia ecmascript-2016


    【解决方案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);
        }
    }
    

    【讨论】:

      【解决方案2】:

      一般建议是尽可能避免继承。改为使用合成。在这种情况下:

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

      【讨论】:

      • 为什么要避免继承?
      • @MatthewJamesDavis 有很多理由避免 deep 继承层次结构。但是,实现多个接口,可以通过组合和委托来完成,是没有问题的。这些问题源于对行为的假设,这些假设难以维护,并且在大多数语言中无法在类型级别记录。随着层次结构深度的增加,这变得更加麻烦。避免过度继承还有很多其他原因。
      【解决方案3】:

      嗯,刚刚找到了解决办法,模块实际上是注入到派生类中,通过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 !!!   
          }
      }
      

      【讨论】:

      • 删除评论,转为回答。
      • 如果你需要向ClassA注入一些东西,ClassA注入是在父注入之前还是之后?
      猜你喜欢
      • 2020-06-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-11-25
      相关资源
      最近更新 更多