How can I get status code using $resource?
Asked Answered
S

3

2

My factory for making request is here:

angular.module('myapp').factory('testResponse',
        ['$http', '$resource', 'AppConfig', '$routeParams', '$rootScope',
            function($http, $resource, $routeParams, $rootScope) {
                $http.defaults.headers.common['Authorization'] = authorizationHeader;
                $http.defaults.headers.post['Content-Type'] = 'application/json';
                return $resource('test.json'), {}, {
                    query: {method: 'GET'}
                };
            }]);

The code in controller is here:

angular.module('myapp').controller('TestCtrl',
        ['$http', '$scope', 'testResponse', 'AppConfig', function TestCtrl($http, $scope, testResponse) {
                testResponse.query(function(data) {
                    console.log(data.status);
                })
            }]);

Ideally it should log the status as in $http request but I am unable to get it for $reource

Stieglitz answered 26/12, 2014 at 10:5 Comment(5)
The point is you don't need the status when dealing with successful requests for resources. And as for logging: An interceptor seems to be the more appropriate tool for that. But you are right: the status is not available.Makalu
What can be done to check cases like 404, 500 or 403 etcStieglitz
Those are failure cases. You deal with them in the failure handler and there you have access to the status. Your example only uses a success handler.Makalu
Thanks @zeroflagL ! I tried This snippet, but I am still not able to handle failure cases. it caused another error "undefined" ie $promise is not a function and when i injected it, I got Unknown provider $promiseprovider<$promiseStieglitz
Another example of why $resource should not be used... accessing the status code on success is not an unusual scenario... this data should be made available by default, not hidden from youLaunalaunce
S
0

I tried use promises with $q to handle this kind of scenario where I had to have more control on failure or success. I refactored the factory like here:

var defObj = $q.defer();
  var testResponse = $resource('https://jsonplaceholder.typicode.com/posts/1', {}, {
    query: {
      method: 'GET'
    }
  });
  testResponse.query().$promise.then(function(data) {
    //you can add anything else you want inside this function
    defObj.resolve(data);
    console.log(defObj, data);
  }, function(error) {
    //you can add anything else you want inside this function
    console.error("Service failure: " + error);
  });
  return defObj.promise;
}

Here is the complete solution in this pen (uses mock json to simulate the response)

Stieglitz answered 11/11, 2016 at 8:38 Comment(2)
I could not get the exact server status codes but this workaround allowed me to look for errors and get more controlStieglitz
refer to my answer below to get the exact server status code.Buddhology
B
6

In service testResponse you can change your return statement to this

return $resource('test.json'), {}, {
    query: {
        method: 'GET',
        transformResponse: function(data, headers,statusCode) {
            console.log(statusCode);//prints 200 if nothing went wrong
            var finalRsponse = {
                data: data,
                responseStatusCode: statusCode
            };
        return finalRsponse;
    }}
};

And in your controller's success method of then(success,error) of testResponse service you can access the status code using data.responseStatusCode.

I have tested it on angularjs-1.2.32 and 1.5.7.

Buddhology answered 16/12, 2016 at 7:53 Comment(0)
H
0
['$http', '$resource', 'AppConfig', '$routeParams', '$rootScope',
        function($http, $resource, $routeParams, $rootScope) {

You have missed AppConfig parameter.

Harriettharrietta answered 26/12, 2014 at 10:56 Comment(0)
S
0

I tried use promises with $q to handle this kind of scenario where I had to have more control on failure or success. I refactored the factory like here:

var defObj = $q.defer();
  var testResponse = $resource('https://jsonplaceholder.typicode.com/posts/1', {}, {
    query: {
      method: 'GET'
    }
  });
  testResponse.query().$promise.then(function(data) {
    //you can add anything else you want inside this function
    defObj.resolve(data);
    console.log(defObj, data);
  }, function(error) {
    //you can add anything else you want inside this function
    console.error("Service failure: " + error);
  });
  return defObj.promise;
}

Here is the complete solution in this pen (uses mock json to simulate the response)

Stieglitz answered 11/11, 2016 at 8:38 Comment(2)
I could not get the exact server status codes but this workaround allowed me to look for errors and get more controlStieglitz
refer to my answer below to get the exact server status code.Buddhology

© 2022 - 2024 — McMap. All rights reserved.