Héctor León February 2016

AngularJS controller promise Then is not a function

i am having troubles making a promise in the controller.

Plunker Editor Sample

This is the code with the module, controller and the factory All works fine less when i callFactory, and wait for the response.

I got in the console an error "Then is not a function" But i don't know what is wrong in the code

angular
    .module('sampleApp', [])
    .controller('SampleController', SampleController)
    .factory('myFactory', myFactory);

////////// FACTORY
    function myFactory () {

    var task = {
      getData : getData,
      counter:  0
    };

    return task;


    // Implementation details //
    // ---------------------- //

    function getData () {
      task.counter ++;
      var response = "FakeData";
      return response;
    }
  }

////////// CONTROLLER
  function SampleController (myFactory, $log) {
    $log.info("Sample controller initialized");

    var vm = this;
    vm.title = "SampleView";
    vm.callFactory = callFactory;
    vm.factoryResponse;

    callFactory();

    // Implementation details //
    // ---------------------- //

    function callFactory () {

      myFactory.getData()
      .then(function (data) {
        vm.factoryResponse = data;
        return vm.factoryResponse;

      })
      .catch(function () {
        $log.error("Ups! We cannot complete the request :(");
      });
    }
  }

Answers


Stepan Kasyanenko February 2016

Because your factory method getData return string. If you want use then, then you method need return $promise. Like this plunker:

////////// FACTORY
function myFactory ($q) {

var task = {
  getData : getData,
  counter:  0
};
var defer = $q.defer();

return task;


// Implementation details //
// ---------------------- //
function getData (randomParameter) {
  task.counter ++;
  var secondString = ", sample factory value"
  var response = randomParameter + secondString;
  defer.resolve(response);
  return defer.$promise;
}}

More about angular $q

Post Status

Asked in February 2016
Viewed 3,877 times
Voted 14
Answered 1 times

Search




Leave an answer