0

I have a web service which returns some data. To prevent code duplication I want to move http request call to angular service:

angular.module('abc', [])
    .factory('def', function () {
        return {
            getData: function () {
                return $http.post('/path/', {});
            }
        };
    });

All is good, but necessary data is inside complicated object, and I have to write every time:

def.getData().then(function (response) {
    scope.obj = response.data.qwe.rty.xyz;
});

What is the easiest way to return promise, which will send value of response.data.qwe.rty.xyz directly to successCallback? And I can write like this:

def.getData().then(function (obj) {
    scope.obj = obj;
});

2 Answers 2

4

The call $http.post('/path/', {}) returns a promise on which you then call then(). Note that then() also returns a promise, so you can chain the calls. Your code could therefore look like this:

angular.module('abc', [])
    .factory('def', function () {
        return {
            getData: function () {
                return $http.post('/path/', {})
                        .then(function(response) {
                            return response.data.qwe.rty.xyz;
                        });
            }
        };
    });
Sign up to request clarification or add additional context in comments.

Comments

2

you can use the deferring behavior that implemented in the $q provider

like so :

angular.module('abc', [])
.factory('def', function ($q) {

    return {
        getData: function () {
             var def = $q.defer
             $http.post('/path/', {}).then(function(response){
               def.resolve(response.data.qwe.rty.xyz)
             });
            return def.promise; 
        }
    };
});

and use it in your controller like :

def.getData().then(function (response) {
 scope.obj = response;
});

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.