0

I have a factory NewEditSvc where I'm trying to share functionality common to NewCtrl and EditCtrl. One thing I'm trying to do is get feeParameters from the server inside the service but this is not working.

angular.module('feeSuitesApp')
.factory('NewEditSvc', function($q, FeeTypesSvc){
  var _feeParameters = {};

  function getParameters(){
    return _feeParameters;
  }

  function setParameters(feeType){
    var promise = $q(function(resolve, reject){
      FeeTypesSvc.resource.get({id: feeType.id, association: 'fee_parameters'}).
      $promise.then(function(data){
        resolve(data);
      }, function(error){
        reject(error);
      })
    });

    promise.then(function(data){
      _feeParameters = data.master;
    });
  }

  return {
    getParameters: getParameters,
    setParameters: setParameters
  }
});

angular.module('feeSuitesApp')
.controller('NewCtrl', function(NewEditSvc, feeType){
  $scope.feeParameters = NewEditSvc.getParameters();
  $scope.feeType = feeType;
  $scope.setParameters = function(feeType){
    NewEditSvc.setParameters(feeType);
  };
  $scope.setParameters($scope.feeType);
});

After my last line $scope.feeParameters is not set. But if I return the promise variable from NewEditSvc.setParameters() and then in my NewCtrl I do the following:

  var promise = $scope.setParameters($scope.feeType);

  promise.then(function(data){
    $scope.feeParameters = data.master;
  });

Then everything works. What am I doing wrong?

isherwood
  • 58,414
  • 16
  • 114
  • 157
Mike Glaz
  • 5,352
  • 8
  • 46
  • 73
  • You are using the explicit-construction anti-pattern as discussed in [this answer](http://stackoverflow.com/a/23803744/548997). – Lex Sep 23 '16 at 16:49
  • I'm guessing I don't need $q. But still, am not able to resolve the promise within the service itself and to return the value to the controller. – Mike Glaz Sep 23 '16 at 20:40
  • The point of that anti-pattern answer is that you shouldn't be resolving the promise in the service - you should be returning the promise and handling the resolving in your controller. – Lex Sep 23 '16 at 20:41

1 Answers1

2

The problem is, that you're not returning your promise in setParameters. https://docs.angularjs.org/api/ng/service/$q/

Just add return promise.

ESP32
  • 8,089
  • 2
  • 40
  • 61