简体   繁体   中英

How to convert xhr request to angular $http request?

I am trying to load image via ajax by the following code which is already Working . I am trying to convert it into angular $http and it doesn't work.

Plain ajax code

var xhr = new XMLHttpRequest();
xhr.open('GET', attr.imageUrl, true);
xhr.responseType = 'blob';
xhr.onload = function(e) {
    element[0].src = window.URL.createObjectURL(this.response);
};

xhr.send();

Angular Code

$http.get(attr.imageUrl, {}, {
    responseType: 'arraybuffer'
})
.success(function(response) {
    var file = new Blob([response]);
    element[0].src = URL.createObjectURL(file);
});

I think it should be:

$http.get({ url: attr.imageUrl, responseType: 'arraybuffer'})
.success(function(response) {
    var file = new Blob([response]);
    element[0].src = URL.createObjectURL(file);
});

Or:

$http.get(attr.imageUrl, {responseType: 'arraybuffer'})
.success(function(response) {
    var file = new Blob([response]);
    element[0].src = URL.createObjectURL(file);
});

Try this:

  $http.get(attr.imageUrl, {responseType: 'arraybuffer'})
  .then(function(response) {
    var file = new Blob([response]);
    element[0].src = URL.createObjectURL(file);
  });

Try This-

$http.get(attr.imageUrl, {responseType: 'arraybuffer'})
  .then(function(response) {
    var file = new Blob([response.data], {
                    type: 'application/octet-binary'
                });
    element[0].src = URL.createObjectURL(file);
  });

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM