【发布时间】:2016-09-25 06:47:26
【问题描述】:
有什么方法可以使用 angularjs 的 $http 访问 xhr.responseURL 吗?
MDN 上有一篇文章解释了如何处理原始 xhr。但我找不到任何使用 angularjs 访问 xhr 对象的解决方案。
【问题讨论】:
标签: javascript angularjs xmlhttprequest
有什么方法可以使用 angularjs 的 $http 访问 xhr.responseURL 吗?
MDN 上有一篇文章解释了如何处理原始 xhr。但我找不到任何使用 angularjs 访问 xhr 对象的解决方案。
【问题讨论】:
标签: javascript angularjs xmlhttprequest
我通过修改$xhrFactory找到了解决办法
angular.module('myApp', [])
.factory('$xhrFactory', ['$rootScope', ($rootScope) => {
return function createXhr(method, url) {
// configure the xhr object that will be used for $http requests
const xhr = new window.XMLHttpRequest({ mozSystem: true });
// attach an handler
xhr.onreadystatechange = () => {
if (xhr.readyState === XMLHttpRequest.DONE) {
/*
you can restrict local xhr calls
if (xhr.responseURL.startsWith('file://')) {
return;
}
*/
// broadcast xhr object to root scope
$rootScope.$broadcast('xhrDone', xhr);
}
};
return xhr;
};
}])
.controller('MyCtrl', ['$scope', ($scope) => {
$scope.$on('xhrDone', (event, xhr) => {
// here is the responseURL
console.log(xhr.responseURL);
});
}])
【讨论】:
$http.get(...)
.then(function(response){
//check response.status/headers/config/statusText
})
【讨论】: