我正在尝试通过我的工厂中的$ http调用从我的JSON文件加载数据,每次运行代码时都会遇到相同的错误。我该如何解决这个问题。
TypeError: undefined is not a function
at Object.getFruitsData (http://localhost/test/JSON/js/controllers.js:12:18)
at new <anonymous> (http://localhost/test/JSON/js/controllers.js:3:16)
at invoke (http://ajax.googleapis.com/ajax/libs/angularjs/1.2.16/angular.js:3869:17)
at Object.instantiate (http://ajax.googleapis.com/ajax/libs/angularjs/1.2.16/angular.js:3880:23)
at http://ajax.googleapis.com/ajax/libs/angularjs/1.2.16/angular.js:7134:28
at http://ajax.googleapis.com/ajax/libs/angularjs/1.2.16/angular.js:6538:34
at forEach (http://ajax.googleapis.com/ajax/libs/angularjs/1.2.16/angular.js:330:20)
at nodeLinkFn (http://ajax.googleapis.com/ajax/libs/angularjs/1.2.16/angular.js:6525:11)
at compositeLinkFn (http://ajax.googleapis.com/ajax/libs/angularjs/1.2.16/angular.js:5986:15)
at compositeLinkFn (http://ajax.googleapis.com/ajax/libs/angularjs/1.2.16/angular.js:5989:13)
我正在使用的代码位于下方。
app.factory('fruitsData', function($http, $log){
return{
getFruitsData: function(succescb){
$http({method:'GET', url:'json/testList.json'})
.succes(function(data){
succescb(data);
})
.error(function(data){
$log.warn(data);
});
}
};
});
app.controller('fruitsController',['$scope','fruitsData', function($scope, fruitsData){
fruitsData.getFruitsData(function(fruits){
$scope.fruits = fruits;
});
}]);
答案 0 :(得分:2)
你永远不会返回数据而你正在创建一个新函数来传递给工厂函数(错误?)
试试这个:
app.factory('fruitsData', ['$http', '$log', function($http, $log) {
return {
getFruitsData: function() {
.success(function(fruitData) {
return fruitData;
})
.error(function(errorMessage) {
//log the error message
});
}
}
}]);
app.controller('fruitController', ['$scope', 'fruitsData', function($scope, fruitsData) {
fruitsData.getFruitsData().then(function(data) {
$scope.fruits = data;
});
}]);