2013-02-07 26 views
4

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

我试过使用承诺(我不是专家),我得到了它背后的逻辑。 我在模块初始化时定义它,并在定义访问令牌 后解析它。现在,我主要关心的是要了解我可以放置该承诺的位置。然后() 方法仅在标记设置时才启动请求。

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

我试图把它挂在resource['_' + action](param, data, success, error)包装函数和其他一些地方,但我觉得自己像瞎了。

非常感谢您的时间。

回答

0

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

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

相关问题