使Angular $资源请求仅在令牌定义后才起作用

时间:2013-02-07 21:43:18

标签: angularjs promise

我正在尝试使用$ resource和请求包装器创建REST客户端。您可以 请参阅下面的代码。一切都很好,但我有一个问题。

RequestWrapper模块用于设置访问令牌(来自片段URI)。 我需要的是能够阻止可能的请求,直到设置访问令牌 来自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']);
}]);

我尝试过使用promises(我不是专家)而且我已经掌握了逻辑。 我在模块初始化期间定义它,然后在访问令牌之后解析它 被定义为。现在,我主要关心的是了解我可以将promise.then()放在哪里 只有在设置了令牌时才让请求开始的方法。

deferred.promise.then(function() { ... })

我试图将它放在包装函数和其他一些地方的resource['_' + action](param, data, success, error)附近,但我觉得自己是盲目的。

非常感谢你的时间。

1 个答案:

答案 0 :(得分:0)

为什么不使用会话服务来提供令牌,比如$scope.token,并在其他控制器中触发$scope.$watch('token', ...)的后续操作?

我建议您阅读AngularJS文档中的$http页面,如果您仍想“阻止”请求,可以使用拦截器(请参阅http://code.angularjs.org/1.1.5/docs/api/ng.$http)。