使用 Aurelia V1,我尝试从
abstract init()
调用 Parent
,其中 init()
在 Child
中实现。 init()
使用一个模块,该模块被注入到 Child
中。
我想我看到了一个错误,因为当 Parent
调用 Child.init()
时,依赖注入初始化尚未完成,但我该如何解决这个问题?
我尝试了多种方法,包括 Aurelia 解析器,例如
lazy
和 parent
。
export abstract class Parent {
protected constructor() {
this.init();
}
protected abstract init();
}
@autoinject()
export class Child extends Parent {
constructor(
private i18n: I18N, // how to import this?
) {
super();
}
protected init() {
this.i18n.tr() // throws error
}
}
Message: Cannot read properties of undefined (reading 'tr')
在这种情况下,我真的不想这样做,因为这些只是普通的实用程序类(验证器)。
export abstract class Parent {
protected constructor() {}
protected abstract init();
}
@autoinject()
export class Child extends Parent {
constructor(
private i18n: I18N,
) {
super();
this.init();
}
protected init() {
this.i18n.tr() // works
}
}
当然,我可以从
Child
调用 init,这样就可以了。尽管如此,我还是试图了解是否有更好的解决方案,或者是否有“奥勒利亚方式”。
export abstract class Parent {
protected constructor(protected i18n: I18N) {}
protected abstract init();
}
@autoinject()
export class Child extends Parent {
constructor(
i18n: I18N,
) {
super(i18n);
}
protected init() {
this.i18n.tr() // works
}
}
同样,这可行,但我不想更改所有现有的子类。还有其他想法吗?
在子方法中使用
Container.instance.get()
方法。
import {Container} from 'aurelia-framework'
@autoinject()
export class Child extends Parent {
private i18n: I18N;
protected init() {
this.i18n = Container.instance.get(I18N);
this.i18n.tr('KEY')
}
}