Angular 1.5.4 $http progress event

空扰寡人 提交于 2019-11-27 21:34:36

In AngularJS v1.5.7 works fine. If you have the chance I recommend upgrade!

...//formData = new FormData(); etc...
var postParams = {
    method: 'POST',
    url: yourURLWS,
    transformRequest: angular.identity,
    uploadEventHandlers: {
        progress: function (e) {
                  if (e.lengthComputable) {
                     $scope.progressBar = (e.loaded / e.total) * 100;
                     $scope.progressCounter = $scope.progressBar;
                  }
        }
    },
    data: formData,
    headers: {'Content-Type': undefined }
};

var sendPost = $http(postParams); //etc...

in HTML you have:

<progress id="progress" max="100" value="{{progressBar}}"></progress>{{progressCounter}}%

Result:

progress result

Well I ended up doing something like this and just handle it myself as the XHR events added to $http dont work for me.

var xhttp = new XMLHttpRequest();
var promise = $q.defer();

xhttp.upload.addEventListener("progress",function (e) {
    promise.notify(e);
});
xhttp.upload.addEventListener("load",function (e) {
    promise.resolve(e);
});
xhttp.upload.addEventListener("error",function (e) {
    promise.reject(e);
});

xhttp.open("post",API_URL + requestParams.url,true);

xhttp.send(requestParams.data);

return promise.promise;

note - I have not worked with NG 1.5.4, the example below is for leveraging existing pre 1.5.4 APIs


The notify(event) API is part of the deferred object when you call $q.defer(). I'm not sure what a practical implementation of this would be in terms of a typical get/put/post call via $http. But if you want to see it in action you can do something like this:

some service API

var mockRqst = function(){
    var d = $q.defer()
    var crnt = 0

    $off = $interval( function(){
        d.notify( crnt )
        crnt += 5

        if (crnt >= 100)
        {
            $interval.cancel( $off ) //cancel the interval callback
            d.resolve( "complete" )
        }
    }

    return d.promise
}    

using the notification

someService.mockRqst()
.then( thenCallback, catchCallback, function( update ){
     console.log("update", update)
})  

codepen - http://codepen.io/jusopi/pen/eZMjrK?editors=1010

Again, I must stress that I'm not entirely sure how you can tie this into an actual external http call.

As seen in the docs here, the third parameter in a promise is a notify function.

notify(value) - provides updates on the status of the promise's execution. This may be called multiple times before the promise is either resolved or rejected.

It can be used like this:

$http(requestData)
    .then(
        function success() {
            console.log('success');
        },
        function error() {
            console.log('error');
        },
        function notify() {
            console.log('notified');
        }
    );
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!