2014-02-15 112 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);