gpt4 book ai didi

angularjs - 如何使用 Angular 访问 $http 中的 XHR?

转载 作者:行者123 更新时间:2023-12-02 23:00:32 24 4
gpt4 key购买 nike

目前我正在尝试用Angular实现上传功能。起初我使用XmlHttpRequest,但后来我将其更改为$http。所以我发现我无法访问XmlHttpRequest 使用 $http 创建进度条。下面是我的代码。关于上传图片时创建进度条有什么建议吗?谢谢。

    $http({
method: 'POST',
url: upload_url,
data: fd,
headers: {'Content-Type': undefined},
transformRequest: angular.identity
})

最佳答案

这里是获取xhr对象的方法:

http://boylesoftware.com/blog/angular-tip-using-the-xmlhttprequest-object/

复制/粘贴:

Normally, an AngularJS application uses the $http service to make calls to back-end services. Sometimes, however, we would like to have access to the underlying XMLHttpRequest object. I can come up with a few use-cases, but the most prominent one is probably being able to track progress of a long request, such as a file upload. To do that, we need to register an event listener on the XMLHttpRequest object for the event that is “in progress.” Surprisingly enough, Angular’s $http service does not in any way expose the underlying XMLHttpRequest object. So, we have to get creative. Here is one way to do it…

The $http service’s config object allows us to add headers to the HTTP request via its “headers” property. That means that at some point $http has to set those headers on the XMLHttpRequest object it uses. The way to do that is to use XMLHttpRequest’s setRequestHeader method. So the idea is to override the setRequestHeader method on the XMLHttpRequest’s prototype and use a special header name to introduce a hook. Let’s begin with that and create a simple Angular module that performs the method substitution in its configuration phase:

angular.module("bsworksXHR", []).config([
function() {
XMLHttpRequest.prototype.setRequestHeader = (function(sup) {
return function(header, value) {
if ((header === "__XHR__") && angular.isFunction(value))
value(this);
else
sup.apply(this, arguments);
};
})(XMLHttpRequest.prototype.setRequestHeader);
}
]);

Now, when we make an $http service call, we can add a header called “XHR” with a function value that will receive the XMLHttpRequest object as its only argument. For example, somewhere else in the application:

$http({

headers: {

__XHR__: function() {
return function(xhr) {
xhr.upload.addEventListener("progress", function(event) {
console.log("uploaded " + ((event.loaded/event.total) * 100) + "%");
});
};
},

},

}).success(…);

Hopefully, future versions of AngularJS will include some official way to access the low-level XMLHttpRequest object, even if limited, such as being able to register event listeners or translating the XMLHttpRequest events into Angular events. Until then, I am using the approach above in my apps.

关于angularjs - 如何使用 Angular 访问 $http 中的 XHR?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16769125/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com