Aurelia&打字稿注入和继承

时间:2015-08-31 07:38:28

标签: dependency-injection typescript aurelia

我正在使用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 <在第一行提供了对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类移到与Home相同的文件中,file3就像这样:

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?

最后我希望将它们放在单独的文件中,但它是一个开始使它工作所以:) 谢谢!

1 个答案:

答案 0 :(得分:3)

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