Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
234 views
in Technique[技术] by (71.8m points)

javascript - angular http: how to call images with custom headers?

In the html view, images are displayed like this:

<img ng-src="{{element.image.url}}"> 

element.image.url points to an url like: /rest_api/img/12345678.

This is working fine, images are displayed.

Now, I add authentication:

Before the user is authenticated, every resources respond with an http error 401, images too. When authentication succeeds, a token is placed in a custom headers and sent with every $http requests, allowing access the resources:

$http.defaults.headers.common['Authorization'] = token; 

This is working fine for Json files loaded with $resource. But the direct links to the images are still 401 after authentication.

How to call the images with custom headers?

Or any advice on how I should do this.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

As said here you can use angular-img-http-src (bower install --save angular-img-http-src if you use Bower).

If you look at the code, it uses URL.createObjectURL and URL.revokeObjectURL which are still draft on 19 April 2016. So look if your browser supports it.

In order to use it, declare 'angular.img' as a dependency to your app module (angular.module('myapp', [..., 'angular.img'])), and then in your HTML you can use http-src attribute for <img> tag.

In your example it would be: <img http-src="{{element.image.url}}">

Of course, this implies that you have declared an interceptor using $httpProvider.interceptors.push to add your custom header or that you've set statically your header for every requests using $http.defaults.headers.common.MyHeader = 'some value';


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...