2017-03-24 72 views
0

我必須在每個請求的HTTP標題中設置一個特殊的值來向服務器進行身份驗證。角度設置圖像加載標題

我有以下代碼:

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

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

的JSON請求一切工作正常,但我與圖像蔣張關係。 你有什麼提示嗎?

回答

1

// 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(); 
+0

解決它。如果你把'setRequestHeader()'的'的open()'調用之前, 會有'未捕獲InvalidStateError:未能執行上 '的XMLHttpRequest' setRequestHeader「:該對象的狀態必須是OPENED.' – webdevbyjoss