Daft
Daft

Reputation: 10964

Adapt the Promise returned in my angular factory

My getData factory is returning a list of people objects from a .json file.

.factory('people', ['$q', function($q) {
    function getData() {
        var deferred = $q.defer();            
        if (event.type == 'exception') { 
            //deferred.reject(result);
        } else {
            deferred.resolve(require('../../../mocks/people.json'));
        }
        return deferred.promise;
    }

    var that = {
        getData: getData
    };        
    return that;
}]);

In my component, I'm outputting this to the console in my browser, as you can see I have to drill down into the Promise to find the values.

enter image description here

Am I missing a step in my factory? I'd like to return just the data contained in my json file, I'd like to avoid doing somthing like than doing something like console.log(Promise.$$state.value) in my component if possible.

I'm returning the angular Promise, do I need to adapt that in some way to just see the data?

Upvotes: 1

Views: 29

Answers (1)

lin
lin

Reputation: 18392

You need to resolve your promise like:

var myApp = angular.module('myApp', []);

myApp.factory('people', ['$q', '$timeout', function($q, $timeout) {
  return that = {
    getData: function getData() {
      var deferred = $q.defer();            
      if (event.type == 'exception') { 
        //deferred.reject(result);
      } else {
        $timeout(function () {
          deferred.resolve({
            'some': 'Data'
          });
        }, 500);
      }
      return deferred.promise;
    }
  };
}]);

myApp.controller('MyCtrl', function(people) {
  people.getData().then((result) => {
    console.log(result)
  })
});

> Demo fiddle

Upvotes: 1

Related Questions