Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/visual-studio-code/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Angularjs 使$resource请求仅在令牌定义之后工作_Angularjs_Promise - Fatal编程技术网

Angularjs 使$resource请求仅在令牌定义之后工作

Angularjs 使$resource请求仅在令牌定义之后工作,angularjs,promise,Angularjs,Promise,我正在尝试使用$resource和请求包装器创建一个REST客户机。你可以 请参阅下面的代码。一切正常,但我有个问题 RequestWrapper模块用于设置访问令牌(来自片段URI)。 我需要的是能够阻止可能的请求,直到设置了访问令牌 从requestWrapper.set()函数 resources.factory('RequestWrapper', ['$http', '$q', function($http, $q) { var scope; var requestWrapper

我正在尝试使用$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']);
}]);
我试着把它放在包装器函数中的
resource[''.+action](param,data,success,error)
和其他一些地方,但我感觉像是瞎子


非常感谢您的时间。

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

我建议您阅读AngularJS文档中的
$http
页面,如果您仍然想“阻止”请求,可以使用拦截器(请参阅)

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