【问题标题】:Making an Angular $resource request work only after token definition仅在令牌定义之后才使 Angular $resource 请求起作用
【发布时间】:2013-06-27 06:36:22
【问题描述】:

我正在尝试使用 $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']);
}]);

我尝试过使用 Promise(我不是专家),并且我得到了它背后的逻辑。 我在模块初始化期间定义它,并在访问令牌之后解决它 被定义为。现在,我主要关心的是了解我可以将 promise.then() 放在哪里 仅在设置令牌时才让请求开始的方法。

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

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

非常感谢您的宝贵时间。

【问题讨论】:

    标签: angularjs promise


    【解决方案1】:

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

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

    【讨论】:

      猜你喜欢
      • 2019-10-06
      • 2015-08-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-11-04
      • 2017-11-24
      • 1970-01-01
      • 2021-02-12
      相关资源
      最近更新 更多