26

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'm trying to run this code, I get "TypeError: EventService.populateData(...).then is not a function".

What am I doing wrong?

1
  • populateData does not return a promise, you dont get then attached to everything by default. it is a part of promise object. You just have to do $scope.items = EventService.populateData(result) Commented Jul 29, 2015 at 18:00

3 Answers 3

31

that service needs to return a promise, not returning the items

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 might not need this though since you could do

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

usually promises are used if you're doing something asynchronously. Like calling an API and waiting for a response. In those cases, the response might take seconds to finish THEN the .then function gets called. in your case if you make that function a promise it will be called almost immediately

EDIT: Here's the link to $q Documentation AngularJS: API: $q

Sign up to request clarification or add additional context in comments.

Comments

5

Return something that has a promise 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; }); }); 

Comments

-11

I have same problem, My device is m1 Mac, I fixed it with npm replace yarn to start

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.