如何使用 $resource 获取状态代码?

Sam*_*esh 1 angularjs angularjs-resource

我提出要求的工厂在这里:

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'}
                };
            }]);
Run Code Online (Sandbox Code Playgroud)

控制器中的代码在这里:

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

理想情况下,它应该记录 $http 请求中的状态,但我无法通过 $reource 获取它

Alo*_*hra 6

在服务中,testResponse您可以将退货声明更改为此

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;
    }}
};
Run Code Online (Sandbox Code Playgroud)

在控制器的 then(success,error) 的 testResponse 服务的成功方法中,您可以使用data.responseStatusCode.

我已经在angularjs-1.2.32和上对其进行了测试1.5.7