How can I get status code using $resource?

我的梦境 提交于 2019-12-06 22:01:38
Alok Mishra

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.

['$http', '$resource', 'AppConfig', '$routeParams', '$rootScope',
        function($http, $resource, $routeParams, $rootScope) {

You have missed AppConfig parameter.

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)

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!