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

I'm developing an Ionic mobile app and getting stuck by mistake

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

The following is the information about my controller and service:

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");
})

Note that I run a gulp script to merge and uglify all JS files before creating the package file.

Any help would be greatly appreciated.

+4
source share
1 answer

As TJ Crowder said, in order to use the โ€œnextโ€ (asynchronous call), you must return a promise from the service, which your controller can later receive:

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;

    }
  } 

})

, , deferred.reject() ( /).

, promises angular: $q.defer

+1

Source: https://habr.com/ru/post/1619731/


All Articles