Created
March 27, 2016 06:26
-
-
Save sebastieno/fb5d305f89acd0faec8a to your computer and use it in GitHub Desktop.
Http request locker for AngularJS
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var IS; | |
(function (IS) { | |
var HttpRequestLocker = (function () { | |
function HttpRequestLocker($http, $q, requestConfig, successCallback) { | |
this.$http = $http; | |
this.$q = $q; | |
this.requestConfig = requestConfig; | |
this.successCallback = successCallback; | |
} | |
HttpRequestLocker.prototype.execute = function () { | |
var _this = this; | |
var deferred = this.$q.defer(); | |
if (!this.waitingDeferred || this.waitingDeferred.length === 0) { | |
this.waitingDeferred = []; | |
this.$http(this.requestConfig).success(function (result) { | |
if (_this.successCallback) { | |
result = _this.successCallback(result); | |
} | |
for (var i = 0; i < _this.waitingDeferred.length; i++) { | |
_this.waitingDeferred[i].resolve(result); | |
} | |
}).error(function (error) { | |
for (var i = 0; i < _this.waitingDeferred.length; i++) { | |
_this.waitingDeferred[i].reject(error); | |
} | |
}).finally(function () { | |
_this.waitingDeferred = null; | |
}); | |
} | |
this.waitingDeferred.push(deferred); | |
return deferred.promise; | |
}; | |
return HttpRequestLocker; | |
})(); | |
IS.HttpRequestLocker = HttpRequestLocker; | |
})(IS || (IS = {})); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
module IS { | |
export class HttpRequestLocker { | |
constructor(private $http: ng.IHttpService, | |
private $q: ng.IQService, | |
private requestConfig: ng.IRequestConfig, | |
private successCallback?: (data : any) => any) { | |
} | |
private waitingDeferred: ng.IDeferred<any>[]; | |
execute(): ng.IPromise<any> { | |
var deferred = this.$q.defer(); | |
if (!this.waitingDeferred || this.waitingDeferred.length === 0) { | |
this.waitingDeferred = []; | |
this.$http(this.requestConfig).success((result) => { | |
if (this.successCallback) { | |
result = this.successCallback(result); | |
} | |
for (var i = 0; i < this.waitingDeferred.length; i++) { | |
this.waitingDeferred[i].resolve(result); | |
} | |
}).error((error) => { | |
for (var i = 0; i < this.waitingDeferred.length; i++) { | |
this.waitingDeferred[i].reject(error); | |
} | |
}).finally(() => { | |
this.waitingDeferred = null; | |
}); | |
} | |
this.waitingDeferred.push(deferred); | |
return deferred.promise; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment