I am trying to create a REST client using $ resource and the request wrapper. You can see the code below. Everything works fine, but I have a problem.
The RequestWrapper module is used to set the access token (from the fragment URI). I need to block possible requests until the access token from the requestWrapper.set () function is 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']); }]);
I tried to use promises (I am not an expert), and I earned the logic behind this. I define it during module initialization and enable it after the access token is defined. Now my main task is to understand where I can put the promise. Then () so that the request starts only when the token is set.
deferred.promise.then(function() { ... })
I tried to put its resource['_' + action](param, data, success, error) in the wrapper function and in some other places, but I feel blind.
Thanks so much for your time.