Sam Sam - 3 months ago 24
AngularJS Question

How can I get status code using $resource?

My factory for making request is here:

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

The code in controller is here:

['$http', '$scope', 'testResponse', 'AppConfig', function TestCtrl($http, $scope, testResponse) {
testResponse.query(function(data) {

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

Sam Sam

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('', {}, {
    query: {
      method: 'GET'
  testResponse.query().$promise.then(function(data) {
    //you can add anything else you want inside this function
    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)