Search code examples
angularjsangularjs-http

Returning complete response object in promise of $http


I have this method in one of my service to make API calls:

this.postData = function(requestURL, requestObj) {
    var deferred = $q.defer();
    console.log("Reached APIService @POST", requestURL);
    $http.post(requestURL, requestObj).success(
        function(data, status, headers, config, statusText) {
            deferred.resolve(data, status, headers, config, statusText);
            console.log(status);
        }).error(
        function(data, status, headers, config, statusText) {
            deferred.reject(data, status, headers, config, statusText);
            console.log(status);
        });
    return deferred.promise;
};

Basically this worked fine, but recently I needed headers data in my code to fetch the error messages in case of exceptions. I am confused how to get that info in returned promise. The above function when called returns only data and rest 4 items are undefined. I believe promise cannot resolve multiple items as above.

Then how do I returned the object in promise as to get the entire information of object returned by API. (As document says the response contains 5 fields, data, status, headers, config, statusText).

Need help..


Solution

  • Promises can only resolve to one value, not five, so the remaining arguments you pass to resolve are silently dropped.

    The good news is that $http.post() itself already returns a promise, so you can just do:

    this.postData = function (requestURL, requestObj) {
        console.log("Reached APIService @POST", requestURL);
        return $http.post(requestURL, requestObj).then(
            function (response) {
                console.log(response.status);
                return response;
            }),
            function (response) {
                console.log(response.status);
                throw response;
            });
    };
    

    Or, without the logging:

    this.postData = function (requestURL, requestObj) {
        return $http.post(requestURL, requestObj);
    };
    

    The response object has properties data, status, headers, and so on. Documentation.