2016-09-15 53 views
2

我正在製作一個有點角度的應用程序來顯示有關英國首屈一指的信息。我想提供一個服務來處理http呼叫,因爲我在頁面上做了幾次,我不想重複一切。這裏是我的table.js TableController,用於建設一個排名表/角度應用http調用定製服務失敗

(function(){ 

angular 
.module("eplApp") 
.controller("tableCtrl", TableController); 

TableController.inject = ['httpService']; 

function TableController(service){ 
    var apiUrl = "http://api.football-data.org/v1/soccerseasons/426/leagueTable"; 

    service.getListFromUrl(apiUrl).then(function(data){ 
var vm.this; 
vm.data = response.data; 
}); 
} 
})(); 

,這裏是我做了運行http請求的服務,service.js:

(function(){ 

angular 
.module("eplApp") 
.factory("httpService", httpService); 

httpService.inject = ['$http']; 

function httpService($http){ 
var apiKey = '971acba677654cdb919a7ccebd5621e2'; 
var vm = this; 
vm.data = []; 

$http({ 
    headers: { 'X-Auth-Token': apiKey }, 
    method: "GET", 
    url: apiUrl 
}).then(function(response) { 
    vm.data = response.data; 
    return vm.data; 
}); 
} 
})(); 

當我運行它時,出現以下錯誤:

Error: [$injector:unpr] http://errors.angularjs.org/1.5.8/$injector/unpr?p0=serviceProvider%20%3C-%20service%20%3C-%20tableCtrl 

我在哪裏錯了?

+1

我認爲你應該開始通過名稱('httpService')注入你的服務,而不是通過它的函數名(HttpService) –

+0

謝謝@ e-shfiyut。我已經提出了你所建議的改變,但錯誤依然存在。我已經更改了上面的代碼以反映更改。 –

+1

你應該閱讀如何在角度創建工廠/服務。工廠應該返回一個對象,它不僅僅是一個函數指針。看@譚樂的回答 –

回答

2

嘗試改變你的服務這樣的:

(function(){ 

    angular 
    .module("eplApp") 
    .factory("httpService", httpService); 

    httpService.$inject = ['$http']; 

    function httpService($http){ 
    return { 
     getListFromURL : getListFromURL 
    } 

    function getListFromURL(apiUrl){ 
     var apiKey = '971acba677654cdb919a7ccebd5621e2'; 
     var vm = this; 
     vm.data = []; 

     return $http({ 
     headers: { 'X-Auth-Token': apiKey }, 
     method: "GET", 
     url: apiUrl 
     }).then(function(response) { 
     vm.data = response.data; 
     return vm.data; 
     }); 
    } 
})(); 

並調用該函數在控制器這樣的:

TableController.$inject = ['httpService']; 

function TableController(service){ 
    var apiUrl = "http://api.footballdata.org/v1/soccerseasons/426/leagueTable"; 

    service.getListFromURL(apiUrl).then(function(data){ 
    //data here is vm.data 
    }); 
} 

希望這有助於!

+1

只是一些關於約定的評論(對這個問題的人也是這樣),工廠名應該是camelCase:'httpService'而不是'HttpService'。 –

+0

感謝您的回答@TanLe,但是我仍然得到同樣的錯誤,這次在不同的地方。我更新了我的問題,以反映您建議的代碼以及我從中獲得的錯誤。 –

+1

嘗試將'inject'更改爲'$ inject'。看起來是錯誤的,所以'httpService'不能被注入到控制器併發生錯誤。 –

2

檢查你使用的控制器,控制器函數參數是httpService,你在裏面使用的是HttpService。請注意,它是大小寫敏感的。

+0

你說得對,謝謝你指出。不過,我仍然得到相同的錯誤。我已經更改了上面的代碼以反映更改。 –