我正在制作一个有点角色的应用程序,以显示有关英超联赛的信息。我想提供一个服务来处理http调用,因为我在页面上做了几次,我不想重复所有事情。这是我的table.js TableController,用于构建联赛表/
(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
我在哪里错了?
答案 0 :(得分:3)
检查你使用的控制器,控制器功能参数是httpService,你用的是HttpService。请查一下,它区分大小写。
答案 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
});
}
希望这有帮助!