user3169945
user3169945

Reputation: 13

angular set Header on image load

i have to set an special Value in the HTTP Header of every Request to authenticate to the Server.

I have the following Code:

<img ng-if="content.image" src="{{img(content.image)}}">

and

var app = angular.module('myApp', []);
app.config(['$httpProvider', function($httpProvider) {
    $httpProvider.defaults.headers.common['Authorization'] = 'myKey';
}])
app.controller('customersCtrl', function($scope, $http) {
    $http.get("http://localhost:8080/myPath") .then(function(response) {
        $scope.content = response.data;
    });

for JSON Requests everything works fine, but i strugle with the Images. Do you have any Hints for me?

Upvotes: 0

Views: 1660

Answers (1)

user3169945
user3169945

Reputation: 13

i solved it with

    // Image returned should be an ArrayBuffer.
var xhr = new XMLHttpRequest();

    //set Authorization Header
    xhr.setRequestHeader("Authorization", 'myKey');
xhr.open( "GET", "https://placekitten.com/500/200", true );

// Ask for the result as an ArrayBuffer.
xhr.responseType = "arraybuffer";

xhr.onload = function( e ) {
    // Obtain a blob: URL for the image data.
    var arrayBufferView = new Uint8Array( this.response );
    var blob = new Blob( [ arrayBufferView ], { type: "image/jpeg" } );
    var urlCreator = window.URL || window.webkitURL;
    var imageUrl = urlCreator.createObjectURL( blob );
    var img = document.querySelector( "#photo" );
    img.src = imageUrl;
};

xhr.send();

Upvotes: 1

Related Questions