Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ionic Controller and Service: "TypeError:... is not a function"

I am developing an Ionic's mobile app and stuck by the error

TypeError: t.getCases(...).then is not a function

The following are my controller and service concerned:

Service

starter.services.factory('appData', function() {

  return {
      getCases: function() {

        var cases =[ 
          {case_id: 1, description: 'headache'},
          {case_id: 2, description: 'fever'},
          {case_id: 3, description: 'stomachache'}
        ];

        return cases;
    }
  } 

})

Controller

starter.controllers.controller('mainViewCtrl', function($scope, appData) {

  appData.getCases().then(function(data){
      $scope.cases = data.cases;
   });  

  console.log("mainViewCtrl completed");
})

Please note that I run the gulp script to merge and "uglify" all JS files before building the package file.

Any help would be much appreciated.

like image 942
Wonderjimmy Avatar asked Nov 08 '22 23:11

Wonderjimmy


1 Answers

As T.J. Crowder said, in order to use "then" (asynchronous call), you have to return a promise from the service, able to fetch in your controller afterwards:

starter.services.factory('appData', function($q) {

  return {
      getCases: function() {

        var deferred = $q.defer();

        var cases =[ 
          {case_id: 1, description: 'headache'},
          {case_id: 2, description: 'fever'},
          {case_id: 3, description: 'stomachache'}
        ];

        //attach data to deferred object
        deferred.resolve(cases);

       //return promise to be catched with "then"
       return deferred.promise;

    }
  } 

})

If you might want to return an error as callback, you might just reject the promise by calling deferred.reject(error) (while error is an optional error message/object).

Here is another good link which helped me to get the concept of asynchronous programming with promises in angular: $q.defer

like image 142
nicost Avatar answered Nov 14 '22 22:11

nicost