Process chunked response with angularjs $http

后端 未结 2 1957
别那么骄傲
别那么骄傲 2021-01-06 02:43

I discoverd recently chunked response. I agree that most of the time we want to work on a full response. But what if I want to work on a chunked response.

How would

2条回答
  •  北恋
    北恋 (楼主)
    2021-01-06 03:26

    You can define a function with the angularjs promise $q wrapping the XMLHttpRequest.

    var chunkedRequestWithPromise = function () {
      var deferred = $q.defer();
      var xhr = new XMLHttpRequest()
      xhr.open("GET", 'https://yoururl.com/chunked', true)
      xhr.onprogress = function () {
        deferred.notify(xhr.responseText);
      }
      xhr.onreadystatechange = function (oEvent) {
        if (xhr.readyState === 4) {
            if (xhr.status === 200) {
                deferred.resolve('success');
            } else {
                deferred.reject(xhr.statusText);
            }
        }
      };
      xhr.send();
      return deferred.promise;
    };
    

    and use it:

    chunkedRequestWithPromise().then(successFn,errorFn,notifyFn);
    

提交回复
热议问题