javascript - How to access $http.get caller variable -
consider simple angularjs code:
$http.get( url ).then(function ( response ) { var cache = new cache(url); cache.response = response; });
my problem above code nondeterministic. sometime url not match when response server.
i edit 10 contact data simultanously. work, cache requests server , put javascript object.
i have written simple service achieve that, suffers above bug.
here code:
angular.module('myapp') .factory('save', function($http, $q) { // private object var cache = function(url) { this._url = url; this.response = {}; this.savedeferred = null; this.savedeferredfulfilled = false; }; cache.prototype.$save = function () { return $http.put( this._url ).then(function (response) { this.response = response; return response; }); }; //public method var draft = { caches: {}, get: function ( url ) { if (draft.caches.hasownproperty(url)) { return draft.caches.url.response; } else { return $http.get( url ).then(function ( response ) { var cache = new cache(url); cache.response = response; return cache; }); } }, save: function(url) { if (draft.caches.url.savedeferred) { if (!draft.caches.url.savedeferredfulfilled) { draft.caches.url.savedeferred.reject(new error('forced timeout')); } draft.caches.url.savedeferred = null; draft.caches.url.savedeferredfulfilled = false; } draft.caches.url.savedeferred = $q.defer(); draft.caches.url.response.version = (parseint(draft.caches.url.response.version) + 1).tostring(); $http.put(url, draft.caches.url.response) .success(function(data) { console.log('some data returned'); console.log(data); draft.caches.url.savedeferredfulfilled = true; draft.savedeferred.resolve(data); }) .error(function(error) { console.log('some error occured in save.creates'); console.log(error); draft.savedeferred.reject(error); }); return draft.savedeferred.promise; } }; return draft; });
it must basic, i'm missing here.
Comments
Post a Comment