AngularJS: 在使用 ng-src 指令时使用 $http 拦截器和 OAuth 令牌
AngularJS: using $http interceptors and OAuth tokens when using ng-src directive
我正在构建一个 Cordova/Phonegap 应用程序,它通过使用 OAuth 的 JSON API 与 Rails 服务器交互。
我已经有很多按钮驱动的功能在工作,我正在使用 http 拦截器来捕获 401 Unauthorized
服务器响应,请求新的 OAuth 令牌然后重试相同的请求。
我的解决方案基本上基于以下代码:https://github.com/witoldsz/angular-http-auth
但是我不知道如何在通过 <img ng-src="image/url">
获取图像时执行所有这些操作。
所以我的问题有两个方面:
1- 如何在 ng-src
请求中注入 OAuth 令牌?
2- 如何拦截更新授权令牌的 401 响应并重试请求?
瓦斯科!你好吗?
我使用了一种类似于此 link 中使用的方法:
https://github.com/dougmoscrop/angular-img-http-src/blob/master/index.js
我将其中的一部分添加到我的控制器中:
function SampleCtrl($scope, $http) {
$scope.ImageUrl = '';
// this method can be on a service ($http or $resource)
$scope.getImageService = function (imageId) {
return $http.get('../MyApi/MyAction/', {
responseType: 'arraybuffer',
params: { id: imageId }
});
};
// this will be called when you need to load the image
$scope.loadImage = function(imageId)
{
$scope.getImageService(imageId).then(function (response) {
var imageBlob = new Blob([response.data], { type: response.headers('Content-Type') });
$scope.ImageUrl = (window.URL || window.webkitURL).createObjectURL(imageBlob);
});
};
$scope.loadImage('image_001');
}
html 看起来像:
<img ng-src="{{ImageUrl}}" alt="alternate" title="title" />
这样做,拦截器将处理 http get 并将 header 包含在 OAuth 令牌中。
要回答这两个问题,您需要一个 http 拦截器,它将 1) 将 Oauth 令牌设置到所有发出的请求中,以及 2) 捕获 401 错误并为您解决它们,刷新并设置身份验证令牌,如果和必要时。
看看这个 excellent post on how to do so. Also read the insightful AngularJs documentation on $http interceptors。都在。
真心希望这些对你有帮助。最好的。
我正在构建一个 Cordova/Phonegap 应用程序,它通过使用 OAuth 的 JSON API 与 Rails 服务器交互。
我已经有很多按钮驱动的功能在工作,我正在使用 http 拦截器来捕获 401 Unauthorized
服务器响应,请求新的 OAuth 令牌然后重试相同的请求。
我的解决方案基本上基于以下代码:https://github.com/witoldsz/angular-http-auth
但是我不知道如何在通过 <img ng-src="image/url">
获取图像时执行所有这些操作。
所以我的问题有两个方面:
1- 如何在 ng-src
请求中注入 OAuth 令牌?
2- 如何拦截更新授权令牌的 401 响应并重试请求?
瓦斯科!你好吗?
我使用了一种类似于此 link 中使用的方法: https://github.com/dougmoscrop/angular-img-http-src/blob/master/index.js
我将其中的一部分添加到我的控制器中:
function SampleCtrl($scope, $http) {
$scope.ImageUrl = '';
// this method can be on a service ($http or $resource)
$scope.getImageService = function (imageId) {
return $http.get('../MyApi/MyAction/', {
responseType: 'arraybuffer',
params: { id: imageId }
});
};
// this will be called when you need to load the image
$scope.loadImage = function(imageId)
{
$scope.getImageService(imageId).then(function (response) {
var imageBlob = new Blob([response.data], { type: response.headers('Content-Type') });
$scope.ImageUrl = (window.URL || window.webkitURL).createObjectURL(imageBlob);
});
};
$scope.loadImage('image_001');
}
html 看起来像:
<img ng-src="{{ImageUrl}}" alt="alternate" title="title" />
这样做,拦截器将处理 http get 并将 header 包含在 OAuth 令牌中。
要回答这两个问题,您需要一个 http 拦截器,它将 1) 将 Oauth 令牌设置到所有发出的请求中,以及 2) 捕获 401 错误并为您解决它们,刷新并设置身份验证令牌,如果和必要时。
看看这个 excellent post on how to do so. Also read the insightful AngularJs documentation on $http interceptors。都在。
真心希望这些对你有帮助。最好的。