![](/img/trans.png)
[英]How to inject dependencies in Aurelia without using ES6 class feature
[英]How to inject in a parent class in Aurelia?
我有一个父类,我想要注入一些模块,然后我有一些派生类,我想使用这些注入的模块。 但是在派生类中,您必须调用不带参数的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 !!!
}
}
好吧,刚刚找到解决方案,模块实际上是在派生类中注入并通过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 !!!
}
}
一般建议是尽可能避免继承。 而是利用构图。 在这种情况下:
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 !!!
}
}
有一个网站,为我解释一个美丽的方式来做到这一点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);
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.