DigguDg DigguDg - 2 months ago 14
JSON Question

AngularJS factory returning State object instead of JSON data from promise

I have made two factory and calling first from second one, consuming second one factory in controller but instead of getting data as JSON, I'm getting data as $$State.
I'm new to angularJS tried many ways but not able to solve, please help.

app.factory('userDetails', ['APIService', '$q', function (APIService, $q) {
getDetails: function () {
var deferred = $q.defer();
var getFunc = function () {
APIService.doGetCall('Masters/employee/username/tarun')
.then(
function (data)
{
deferred.resolve(data);
},
function (data, status, headers, config)
{
deferred.reject('There was an error creating object'); })
return deferred.promise;
}
var a = getFunc();
return a;

}
}

vm.user = userDetails.getDetails();
console.log("user",vm.user);


response is as per below snippet

Response

Answer

You should be using .then function to get response there. Rather I'd say you don't need to create extra promise, its an anti-pattern. Where you could utilize the promise return by doGetCall method directly.

app.factory('userDetails', ['APIService', '$q', function(APIService, $q) {
  getDetails: function() {
    var getFunc = function() {
      return APIService.doGetCall('Masters/employee/username/tarun');
    }
    var a = getFunc();
    return a;
  }
}]);

vm.user = userDetails.getDetails().then(function(response){
    console.log(response.data);
    vm.user = response.data;
    console.log("user", vm.user);
}, function(error){
    console.log(error)
}).catch(exceptionHandler);
Comments