如何使用$ resource获取状态代码? [英] How can I get status code using $resource?
本文介绍了如何使用$ resource获取状态代码?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我的提出要求的工厂在这里:
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);
})
}]);
理想情况下,它应该记录$ http请求中的状态,但我无法获得$ reource的状态
Ideally it should log the status as in $http request but I am unable to get it for $reource
推荐答案
我尝试对$ q使用诺言来处理这种情况,在这种情况下,我必须对失败或成功进行更多控制. 我像下面这样重构工厂:
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;
}
这是这支笔中的完整解决方案(使用模拟json来模拟响应)
Here is the complete solution in this pen (uses mock json to simulate the response)
这篇关于如何使用$ resource获取状态代码?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文