2013-02-07 24 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)。

相關問題