打字稿角度依赖注入失败

时间:2014-02-15 00:14:50

标签: angularjs typescript

我有一个应用程序

/// <reference path="../Scripts/angular.d.ts" />
/// <reference path="testCtrl.ts" />
/// <reference path="testSvc.ts" />
angular.module('testApp', []);
angular.module('testApp').constant('url','http://whatever');
angular.module('testApp').factory(
'testSvc', ['$http', 'url', testApp.testSvc]);
angular.module('testApp').controller(
'testCtrl', ['testSvc', testApp.testCtrl]);

和控制器

/// <reference path="../Scripts/angular.d.ts" />
/// <reference path="testSvc.ts" />
module testApp{
export class testCtrl {
    public someText:string;
    public httpData:any;
    public urlName:string;
    private data:IData;

    static $inject = ['testSvc'];

    constructor(testSvc) {
        this.someText = 'I am in scope'
        this.data = testSvc.getData();
        this.httpData = {
            putFunc: this.data.putFunc,
            expectPUTFunc: this.data.expectPUTFunc
        }
        this.urlName = this.data.urlName;
    }
}}

和服务

/// <reference path="../Scripts/angular.d.ts" />
/// <reference path="testCtrl.ts" />
interface IData{
urlName:string;
putFunc:string;
expectPUTFunc:string;
}
module testApp{
export class testSvc {
    public data:IData;



    static $inject = ['$http', 'url'];

    constructor(private $http, url) {
        this.data = {
            urlName:url,
            putFunc: typeof $http.put,
            expectPUTFunc: typeof $http.expectPUT
        }
    }

    getData(){
        return this.data;
    }
}}

和我的html中的这些脚本声明

<script type="text/javascript" src="../Scripts/angular.js"></script>
<script src="testSvc.js"></script>
<script src="testCtrl.js"></script>
<script src="testApp.js"></script>

当我运行此应用程序时,控制器永远不会收到它对testSvc.getData()的依赖,因为testSvc未定义。我哪里错了?

2 个答案:

答案 0 :(得分:3)

工厂必须返回服务工厂函数,但是您将返回Service类而不实例化它。您需要更改代码以创建传递$httpurl的实例,如下所示:

angular.module('testApp').factory('testSvc', 
  ['$http', 'url', ($http, url) => new testApp.testSvc($http, url)]);

也只是一个注释,但您没有将getData()的返回类型指定为IData,因此这会产生警告。 getData() : IData

答案 1 :(得分:2)

您可以将testSvc课程保持不变,并使用service(class)代替factory(fn)。服务注册您的构造函数,因此您不必新建它并在三个不同的地方提供您注入的服务。

angular.module('testApp').service('testSvc', testApp.testSvc);