Created
June 20, 2017 22:05
-
-
Save bripc/e6e8118028baf5465f7d688ae467251a to your computer and use it in GitHub Desktop.
Workaround for OfflineJS and AngularJS offline compatibility. Interceptor that handles creating a queue of requests to resend upon connection being reestablished.
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
(function () { | |
'use strict'; | |
angular | |
.module('app') | |
.factory('OfflineInterceptor', ["$q", function ($q) { | |
// queue for saving requests to be sent to the server when connection is down | |
var queue = []; | |
return { | |
request: function (config) { | |
var deferred; | |
// Offline still checks for offline state | |
Offline.check(); | |
// when Offline determines the connection is back up, send all the requests in the queue | |
Offline.on("up", function () { | |
// if they sent requests while offline, resend them now | |
if (queue.length) { | |
angular.forEach(queue, function (req) { | |
req.promise.resolve(req.config); | |
}); | |
queue = []; | |
} | |
}); | |
if (Offline.state === "down") { | |
// in this example, saving only non-get requests to send to the server later | |
if (config.method !== "GET") { | |
// create and return a promise for resolving once the connection is restored | |
deferred = $q.defer(); | |
queue.push({ | |
config: config, | |
promise: deferred | |
}); | |
return deferred.promise; | |
} | |
} | |
return config; | |
} | |
}; | |
}]) | |
.config(["$httpProvider", function ($httpProvider) { | |
$httpProvider.interceptors.push('OfflineInterceptor'); | |
}]); | |
}()); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment