Why is this not a function?

service.js

.factory('EventService', function ($http, $cordovaSQLite) { return { //some code here.. populateData: function (data) { var items = []; for (i = 0; i < data.length; i++) { items.push(data[i]); } return items; } } }) 

controller.js

 .controller('NearCtrl', function ($scope, $http, $cordovaSQLite, EventService) { EventService.getDataFromDB().then(function (result) { if (result.length > 0) { EventService.populateData(result).then(function (items) { $scope.items = items; }) } else { EventService.getDataFromApi().then(function () { EventService.getDataFromDB().then(function (result) { EventService.populateData(result).then(function (items) { $scope.items = items; }) }) }) } }); }) 

When I try to run this code, I get "TypeError: EventService.populateData (...). Then this is not a function."

What am I doing wrong? Thank you

+9
angularjs
source share
2 answers

that the service should return the promise, and not return the elements

 populateData: function(data) { var deferred = $q.defer(); var items = []; for (i = 0; i < data.length; i++) { items.push(data[i]); } deferred.resolve(items); return deferred.promise; } 

you may not need it, although you could do

 var items = EventService.populateData(result); //Do something with items here 

usually promises are used if you do something asynchronously. Like an API call and waiting for a response. In these cases, the answer may take seconds to complete THEN, after which the .then function will be called. in your case, if you make this function a promise, it will be called almost immediately

EDIT: here is a link to $ q AngularJS Documentation : API: $ q

+19
source share

Return what the promise has, or just change your calling code:

 populateData: return $http.get("www"); 

or

 EventService.getDataFromApi().then(function () { EventService.getDataFromDB().then(function (result) { var response = EventService.populateData(result); $scope.items = response; }); }); 
+1
source share

All Articles