2014-02-15 111 views
1

我在我的HTML应用程序 打字稿角依赖注入失败

/// <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; 
    } 
}} 

这些脚本声明

<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是不确定的。我哪里错了?

+0

你为什么对角顶分层你自己的模块?你从这个额外的复杂层面,额外的全局状态和语义重复中获得了什么好处? – yangmillstheory

回答

3

工厂必须返回一个服务工厂函数,但是您返回的是Service类而不实例化它。你需要改变你的代码来创建一个通过了$httpurl一个实例,像这样:

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

也只需一张纸条,但你没有指定的getData()返回类型为IData所以这会产生警告。 getData() : IData

+0

谢谢,谢谢。我正在关注我在GitHub上找到的ts-ng模板(https://github.com/santialbo/AngularJS-TypeScript-Project-Template),并且该应用程序具有注册服务功能,该服务使用 services.push( ()=> new app.services [className]()); 如果该服务没有依赖关系,但我不认为这很有用,那么这就行得通了。我无法弄清楚什么是错的。 也感谢您的类型更正。我不能习惯TypeScript在变量或函数之后而不是之前的类型。 – pthalacker

2

你可以只留下您testSvc类相同,并使用service(class)代替factory(fn)的。一个服务注册你的构造函数,所以你不必新建它,并在三个不同的地方提供你的注入服务。

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