2015-10-01 17 views
-2

編輯:這個問題已棄用。請參閱How to set a variable from an $http call then use it in the rest of the application WITHOUT making the whole application asynchronous

我有一個factory$http是未定義的。我以爲DI會爲我定義它。

我在做什麼錯?我在這裏犯了什麼根本的錯誤理解?

額外的零件()導致函數在配置階段被調用。但URL是我希望馬上爲整個應用程序提供的屬性。

angular.module('myApp').factory('Test',['$http'], 
    { 
    URL: (function ($http) { 
     $http.get('http:www.myserver.com/api/thing').then(function (response) { }); 
    })() // extra parens makes the function run right off the bat 
    } 
); 

我該如何解決?

+2

'//額外的括號的功能,使功能運行正確關閉bat'它使其將URL屬性設置爲undefined ... –

+2

提示:當您使用該數組語法指定依賴項時,數組中的最後一項需要是一個函數:'angular.module('myApp')。factory ('Test',['$ http',function($ http){...});' –

回答

1

您的工廠定義是錯誤的。使用您有內聯依賴注入風格,第二個參數應該是一個數組,其最後一個元素是消耗以前依賴

angular 
    .module('myApp') 
    .factory('Test', ['$http', function ($http) { 
     //return an object that represents your service's API 
     return { 
      URL: function() { 
       $http.get('http:www.myserver.com/api/thing').then(function (response) { }); 
      } //pass the actual function to invoke later 
     }; 
    }]); 
+0

耶穌!謝謝。! – toddmo

0

我看來像你的語法是錯誤的,應該是:

angular.module('myApp').factory('Test',['$http',function($http){ 
    return { 
     URL: function() { 
      $http.get('http:www.myserver.com/api/thing').then(function (response) { }); 
     } //pass the actual function to invoke later 
    }; 
}]); 
+0

差不多。只需從函數params –

+0

中的'$ http'刪除引號是的,對不起,我衝了一下答案... –

+0

它仍然是未定義的。我將這個'Test'服務列爲控制器的依賴項,並嘗試在控制器中使用'Test.URL'。 '$ http'在使用它的控制器行之前被命中,並且它仍然是未定義的。 – toddmo

1

這句法看起來並不完全正確。嘗試像這樣

angular.module('myApp').factory('Test',['$http', function($http) { 
}]);