【问题标题】:Aurelia & Typescript injection and inheritanceAurelia & Typescript 注入和继承
【发布时间】:2015-11-25 04:29:53
【问题描述】:

我正在使用 Aurelia 和 Typescript,我正在尝试实现以下目标:拥有一个名为 Parent 的基类,在一个名为 Child 的类中扩展该类,然后在其中注入一个 Child 的实例另一个班级。 这是设置:

//file1

export class Parent {
    constructor() {
        debugger;
    }
}

//file2
import {Parent} from "file1";
export class Child extends Parent {
    constructor() {
        super();
        debugger;
    }
}

//file3
import {inject} from "aurelia-framework";
import {Child} from "file2";

@inject(Child)
export class Home {
    private child: Child;
    constructor(_child: Child) {
        this.child = _child;
        debugger;
    }
}

但是,当我这样做并实例化 Home 时,我收到以下错误:

Uncaught SyntaxError: Unexpected token <

连同ERROR [app-router] Router navigation failed, and no previous location could be restored.

现在,第一个错误 Uncaught SyntaxError: Unexpected token &lt; 在第一行给了我对 file1.js 的引用。 (奇怪的是包含应用程序索引中的 html 代码)。

现在,如果我从file3 中取出注射,然后做这样的事情:

//@inject(Child)
export class Home {
    private child: Child;
    constructor() {
        this.child =  new Child(); //here I don't inject, I just 
//instantiate a new object of type Child - still the same error
        debugger;
    }
}

我得到完全相同的错误,所以它似乎与注入无关。

那么,我怎样才能有一个名为Parent 的基类,在一个名为Child 的类中扩展这个类,然后在另一个类中注入一个Child 的实例?

或者我的方法有什么不对?

谢谢!

更新:调用new Child() 的简单事实破坏了一切,无论是在页面加载时、在构造函数中还是在按钮。加载时会中断。

   buttonMethod(){
     var x = new Child();  //it breakes the same way
}

现在,如果我将Child 类与Homefile3 移动到同一文件中,则如下所示:

import {inject} from "aurelia-framework";
import {Parent} from "file1";

export class Home {
    child: Child;
    constructor() {
        this.child = new Child();
        debugger;
     }
}


export class Child extends Parent {
    constructor() {
        super();
        debugger;
    }
}

我像这样实例化它,它可以工作。但是,当我尝试注入它时,所以:

import {inject} from "aurelia-framework";
import {Parent} from "file1";

@inject(Child)
export class Home {
    child: Child;
    constructor(_child: Child) {
        this.child = _child;
        debugger;
     }
}


export class Child extends Parent {
    constructor() {
        super();
        debugger;
    }
}

我得到:inner error: Error: key/value cannot be null or undefined. Are you trying to inject/register something that doesn't exist with DI?

最后我想将它们放在单独的文件中,但这是让它工作的开始:) 谢谢!

【问题讨论】:

  • 您是否尝试将完整的absolute path 设置为file1absolute/path/to/file1 之类的东西?
  • 也看看“@autoInject”

标签: dependency-injection typescript aurelia


【解决方案1】:

好的,所以 Typescript 编译器找到了 file1,因为它在 .csproj 文件中,所以它不需要完整路径,但是在运行时,Aurelia framework 找到了文件(在 typescript 代码被转译后) 类似localhost/file1.js。所以你有 2 种可能性:要么在 typings 文件夹中创建一个 tsd.json(假设你使用的是 AMD 模块系统),在其中为你的打字稿定义设置绝对路径,或者在导入自定义类型时总是写完整路径。

【讨论】:

    猜你喜欢
    • 2023-03-12
    • 2014-10-14
    • 1970-01-01
    • 2011-11-12
    • 1970-01-01
    • 1970-01-01
    • 2023-03-28
    • 1970-01-01
    • 2019-01-27
    相关资源
    最近更新 更多