我正在尝试使用 $resource 和请求包装器创建一个 REST 客户端。你可以
请参阅下面的代码。一切正常,但我有一个问题。
RequestWrapper 模块用于设置访问 token (来自片段 URI)。
我需要的是能够阻止可能的请求,直到设置访问 token
来自 requestWrapper.set() 函数。
resources.factory('RequestWrapper', ['$http', '$q', function($http, $q) {
var scope;
var requestWrapper = {};
var deferred = $q.defer();
// get info about the token
requestWrapper.get = function() { return scope; };
// Set the info related to the token
requestWrapper.set = function(newScope) {
scope = newScope;
$http.defaults.headers.common['Authorization'] = 'Bearer ' + scope.token.access_token;
// Here I resolve the promise
deferred.resolve(true);
};
requestWrapper.wrap = function(resource, actions) {
var wrappedResource = resource;
for (var i=0; i < actions.length; i++) { request(wrappedResource, actions[i]); };
return wrappedResource;
};
var request = function(resource, action) {
resource['_' + action] = resource[action];
resource[action] = function(param, data, success, error) {
if (scope && scope.token.expires_at < new Date()) {
window.location.replace(scope.endpoint)
} else {
return resource['_' + action](param, data, success, error);
}
};
};
return requestWrapper;
}]);
// Example on using the Request Wrapper
resources.factory('Profile', ['RequestWrapper', '$resource', function(RequestWrapper, $resource) {
var resource = $resource(endpoint + '/me');
return RequestWrapper.wrap(resource, ['get']);
}]);
我尝试使用 Promise(我不是专家),并且我得到了它背后的逻辑。
我在模块初始化期间定义它,并在访问 token 之后解决它
被定义为。现在,我主要关心的是了解我可以将 promise.then() 放在哪里
仅在设置 token 时才让请求启动的方法。
deferred.promise.then(function() { ... })
我试着把它放在
resource['_' + action](param, data, success, error)
在包装函数和其他一些地方,但我觉得自己很盲目。非常感谢您的时间。
最佳答案
为什么不使用 session 服务来提供 token ,例如 $scope.token
并使用 $scope.$watch('token', ...)
触发后续操作在其他 Controller 中?
我建议您阅读 $http
AngularJS 文档中的页面,如果您仍然想“阻止”请求,您可以使用拦截器(参见 http://code.angularjs.org/1.1.5/docs/api/ng.$http)。
关于angularjs - 仅在 token 定义后才使 Angular $resource 请求起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14761546/