angular http:如何使用自定义标题调用图像? [英] angular http: how to call images with custom headers?
问题描述
在 html 视图中,图像显示如下:
In the html view, images are displayed like this:
<img ng-src="{{element.image.url}}">
element.image.url
指向一个 url,如:/rest_api/img/12345678
.
element.image.url
points to an url like: /rest_api/img/12345678
.
这工作正常,显示图像.
现在,我添加身份验证:
在用户通过身份验证之前,每个资源都以 http 错误 401 响应,图像也是如此.当身份验证成功时,一个令牌被放置在一个自定义标头中,并与每个 $http 请求一起发送,允许访问资源:
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;
这适用于加载了 $resource 的 Json 文件.但是图片的直接链接经过认证后还是401.
This is working fine for Json files loaded with $resource. But the direct links to the images are still 401 after authentication.
如何调用带有自定义标题的图片?
或者关于我应该如何做的任何建议.
Or any advice on how I should do this.
推荐答案
正如所说的这里你可以使用angular-img-http-src (bower install --save angular-img-http-src
如果你使用 Bower).
As said here you can use angular-img-http-src (bower install --save angular-img-http-src
if you use Bower).
如果您查看代码,它使用 URL.createObjectURL
和 URL.revokeObjectURL
是 2016 年 4 月 19 日的仍然草稿.所以 看看你的浏览器是否支持.
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.
为了使用它,将 'angular.img'
声明为您的应用模块的依赖项 (angular.module('myapp', [..., 'angular.img''])
),然后在您的 HTML 中,您可以将 http-src
属性用于 <img>
标签.
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.
在您的示例中,它将是:<img http-src="{{element.image.url}}">
In your example it would be: <img http-src="{{element.image.url}}">
当然,这意味着您已经声明了一个 interceptor 使用 $httpProvider.interceptors.push
添加自定义标头或使用 $http.defaults.headers.common.MyHeader = 'some value';
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';
这篇关于angular http:如何使用自定义标题调用图像?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!