Cud*_*dos 7 angularjs bearer-token
我是Angular的新手,并且继承了旧版本,所以请多多包涵。
我的Angular 1.5.7应用程序需要从我的API服务器获取文件,该文件受Bearer Token Authentication保护https://somedomain.com/api/doc/somefile.pdf
。因此,我需要像这样设置标题:Authorization: Bearer xxxxxxxxxxxx
。
我试图用Postman请求文件并设置标题,Authorization: Bearer xxxxxxxxxxxx
并且可以工作。
在Angular 1.5.7中,我在view.html中有一个这样的链接<a href="{{url}}" ng-show="url" target="_blank"> PDF</a>
,其中{{url}}
= https://somedomain.com/api/doc/somefile.pdf
。
问题是我不知道如何向链接添加标题。我认为这是不可能的。我必须做一个这样的链接:<a>PDF</a>
单击Angular接管后,打开一个新窗口,然后将文件加载到那里。
我看过这些可能会解决我问题的堆栈溢出问题,但是老实说,我不知道如何实现解决方案:
更新
我的解决方案是使用以下代码制定指令。之所以起作用,是因为单击链接时,当前窗口已经设置了授权标头,因此授予了对该文件的访问权限。
<a href="https://somedomain.com/api/doc/somefile.pdf" ng-click="openPdf($event)">PDF</a>
function openPdf($event) {
// Prevent default behavior when clicking a link
$event.preventDefault();
// Get filename from href
var filename = $event.target.href;
$http.get(filename, {responseType: 'arraybuffer'})
.success(function (data) {
var file = new Blob([data], {type: 'application/pdf'});
var fileURL = URL.createObjectURL(file);
// Open new windows and show PDF
window.open(fileURL);
});
}
Run Code Online (Sandbox Code Playgroud)
您不能使用拦截器。单击的链接将由浏览器请求处理,而不是系统。您需要将单击事件处理程序(使用 event.preventDefault() 方法)附加到此链接,并使用您自己的函数发送 get 请求。这会将标头添加到请求中
归档时间: |
|
查看次数: |
5463 次 |
最近记录: |