我正在尝试将JavaScript代码重写为TypeScript,但是在尝试将类导入另一个TypeScript文件时遇到了一些问题。
这以前是在jQuery命名空间上完成的,在这种情况下效果很好。
我的情况是:
文件布局:
import { Commands } from './funnel.commands'
var commands = new Commands(); /*<--- problematic line*/
export class Layouts {
loadHtmlSubLayout(done: Function, layoutname: string): void {
/*...*/
commands.CloseSubLayout();
/*...*/
};
closeSubLayout(layoutContent): void {
/*...*/
};
}
文件命令:
import { Layouts } from './funnel.layouts'
var layouts = new Layouts();
export class Commands {
GotoLayout(el, cmd: CommandObj): void {
/*...*/
layouts.loadSpecificLayout(layouts.onLayoutSwitched, layoutName);
};
CloseSubLayout(): void {
/*...*/
if ($subLayoutContent.length !== 0) {
layouts.closeSubLayout($subLayoutContent);
}
};
}
每当我尝试运行此命令时,都会出现错误“命令不是构造函数”。我如何才能确保这种方法有效而不必四处移动方法?
答案 0 :(得分:1)
这2个模块中的一个必须回退并使用async / lazy init另一个模块,以打破循环导入链。
在您的示例中,我假设在Commands
之前使用Layouts
。因此,您可以执行以下操作:
文件funnel.commands
import { Layouts } from './funnel.layouts'
var layouts = new Layouts
export class Commands {
CloseSubLayout(): void {
layouts.closeSubLayout({});
};
}
文件funnel.layouts
import { Commands } from './funnel.commands'
var commands: Commands
setTimeout(() => {
commands = new Commands()
})
export class Layouts {
loadHtmlSubLayout(): void {
commands.CloseSubLayout();
};
closeSubLayout(layoutContent): void {
console.log('You just called Layouts.closeSubLayout()')
};
}
另一方:
import { Commands } from './funnel.commands'
var commands = new Commands()
commands.CloseSubLayout()
上面的解决方案应该可以工作,但是循环依赖仍然是一种反模式。由于您正在重写代码库,因此最好重构该部分。我建议使用某种依赖注入模式。
文件dependencies
export const dependencies: any = {
_register(map: any) {
Object.assign(this, map)
}
}
文件funnel.commands
import { dependencies as dep } from './dependencies'
export class Commands {
CloseSubLayout(): void {
dep.layouts.closeSubLayout({});
};
}
文件index
import { Commands } from './funnel.commands'
import { Layouts } from './funnel.layouts'
import { dependencies } from './dependencies'
var commands = new Commands()
var layouts = new Layouts()
dependencies._register({ commands, layouts })