2015-12-12 107 views
6

我有一個服務,包裝$ http與我的函數返回一個延期的對象。

我的界面:

export interface MyServiceScope { 
    get: ng.IPromise<{}>; 
} 

我的類:

export class MyService implements MyServiceScope { 

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

    constructor(private $http: ng.IHttpService, 
       private $log: ng.ILogService, 
       private $q: ng.IQService) { 
     this.$http = $http; 
     this.$log = $log; 
     this.$q = $q; 
    } 

    get(): ng.IPromise<{}> { 
     var self = this; 
     var deferred = this.$q.defer(); 

     this.$http.get('http://localhost:8000/tags').then(
      function(response) { 
       deferred.resolve(response.data); 
      }, 
      function(errors) { 
       self.$log.debug(errors); 
       deferred.reject(errors.data); 
      } 
     ); 

     return deferred.promise; 
    } 
} 

編譯與下面的錯誤而失敗:

myservice.ts(10,18): error TS2420: Class 'MyService' incorrectly implements interface 'MyServiceScope'. 
    Types of property 'get' are incompatible. 
     Type '() => IPromise<{}>' is not assignable to type 'IPromise<{}>'. 
      Property 'then' is missing in type '() => IPromise<{}>'. 

作爲參考,從DefinitelyTyped here is the IPromise定義。 IQService.defer()調用返回IDeferred對象,然後deferred.promise返回IPromise對象。

我不確定是否在界面中使用了錯誤的定義,或者沒有以相同的方式返回延遲對象。任何投入將不勝感激!

+2

你可以跳過所有的'this。 =;'線也 –

回答

3

在您的界面中,您定義了一個屬性get,並且在服務實現中它是一個函數get()。你可能想要的是一個函數,所以界面應該是:

export interface MyServiceScope { 
    get(): ng.IPromise<{}>; 
} 
+2

哇,這是尷尬。這絕對是問題。感謝您的快速幫助! – charcoalhobo