我正在尝试将模板自动连接到 inversifyjs 容器,但无论我尝试什么,它都不起作用。请帮忙?
private templates = [
{file: './component.html.tpl', obj: 'HtmlTemplate'},
{file: './component.tpl.ts', obj: 'ComponentTemplate'}
];
private container = new Container();
bind(){
// original and working code
// this.container.bind<ITemplate>('HtmlTemplate').to(HtmlTemplate);
// this.container.bind<ITemplate>('ComponentTemplate').to(ComponentTemplate);
this.templates.forEach(template => {
import(template.file).then(mod => {
console.log(mod.default, template);
// is this correct (seems to work) =>
this.container.bind<ITemplate>(template.obj).to(mod.default);
console.log('bound =>', mod.default);
});
});
}
和文件 ./component.html.tpl
@injectable() export default class HtmlTemplate implements ITemplate { ... }
和 ./component.ts.tpl
@injectable() export default class ComponentTemplate implements ITemplate { ... }
完全按预期记录到控制台:
[Function: HtmlTemplate] { file: './component.html.tpl', obj: 'HtmlTemplate' }
[Function: ComponentTemplate] { file: './component.tpl.ts', obj: 'ComponentTemplate' }
但我真的很期待 foreach 语句中的代码:
this.container.bind<ITemplate>(template.obj).to(mod.default);
等同于:
this.container.bind<HtmlTemplate>('HtmlTemplate').to(HtmlTemplate);
this.container.bind<ComponentTemplate>('ComponentTemplate').to(ComponentTemplate);
但是当我尝试在另一个循环中解决它时:
this.templates.forEach(template => {
const tpl = this.container.get<ITemplate>(template.obj);
...
它抛出一个错误:
Error: No matching bindings found for serviceIdentifier HtmlTemplate
有谁知道如何解决这个问题?