aWebDeveloper
aWebDeveloper

Reputation: 38352

How to convert xhr request to angular $http request?

I am trying to load image via ajaxby 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);
});

Upvotes: 1

Views: 2200

Answers (3)

Shailendra Singh Deol
Shailendra Singh Deol

Reputation: 637

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);
  });

Upvotes: 0

Jyoti Prakash
Jyoti Prakash

Reputation: 1260

Try this:

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

Upvotes: 1

michelem
michelem

Reputation: 14590

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);
});

Upvotes: 1

Related Questions