简体   繁体   中英

How to handle Angular $http result in a Factory

I am using a Angular factory, service and a controller. I use the service to $http get data from a url, send it to the factory who then handles the response data and sends a object to the controller:

Service:

module.exports = function($http, $q){
  return {
    getOptions: function () {
      var deferred = $q.defer();
      $http({ method: "GET", url: AppAPI.url + 'acf/v2/options/' })
        .success(function (data, status, headers, config) {
          deferred.resolve(data);
        }).error(function (data, status, headers, config) {
          deferred.reject(status);
        });
      return deferred.promise;
    }
  }
};

Factory:

module.exports = function(optionsService){
  var options = {};
  var getOptions = optionsService.getOptions();

  getOptions.then(function(items){
    options = items;
  });

  return options;
};

Controller:

module.exports = function($scope, $http, optionsFactory){

  console.log(optionsFactory);

};

But the Factory returns an empty options to the controller. How would you assign the items from the promise to the options object which get's returned to the controller?

UPDATE

Here is a fiddle

Would appreciate the help :)

Could you try changing

var getOptions = optionsService.getOptions();
// to
var getOptions = optionsService.getOptions;

If you created a plunkr/fiddle, that would help a bit.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM