Skip to content

Instantly share code, notes, and snippets.

@migajek
Last active June 1, 2016 12:22
Show Gist options
  • Save migajek/dede8e9184a087e19bd9 to your computer and use it in GitHub Desktop.
Save migajek/dede8e9184a087e19bd9 to your computer and use it in GitHub Desktop.
Angular + ServiceStack's SSE
factory('sse', ['$rootScope', '$http', function($rootScope, $http) {
// https://gist.github.com/migajek
var splitOnFirst = function (s, c) { if (!s) return [s]; var pos = s.indexOf(c); return pos >= 0 ? [s.substring(0, pos), s.substring(pos + 1)] : [s]; };
return {
start: function(handlers) {
var opt = {};
var sse = new EventSource('/event-stream');
sse.addEventListener('message', function(e) {
var parts = splitOnFirst(e.data, ' ');
var selector = parts[0];
var msg = parts[1] ? parts[1].trim() : null;
if (msg && msg.indexOf("{") == 0 && msg.indexOf("}") == msg.length-1)
msg = JSON.parse(msg);
else
msg = msg.replace(/^"(.*)"$/, "$1").replace(/\\"/g, '"');
parts = splitOnFirst(selector, '.');
var handled = false;
var cmd = "";
// currently handles only cmd.OnConnect
if (parts.length > 1 && parts[0] == "cmd")
{
cmd = parts[1];
if (cmd == "onConnect")
{
if (angular.isObject(msg))
angular.extend(opt, msg);
if (opt.heartbeatUrl) {
if (opt.heartbeat) {
window.clearInterval(opt.heartbeat);
}
opt.heartbeat = window.setInterval(function () {
$http.post(opt.heartbeatUrl, null, function(r) {});
}, parseInt(opt.heartbeatIntervalMs) || 1000);
}
if (opt.unRegisterUrl) {
if ((!('unregisterWhenStateChange' in opt)) || (opt.unregisterWhenStateChange))
{
var stopHeartBeatAndUnregister = function () {
if (opt.heartbeat) {
window.clearInterval(opt.heartbeat);
}
sse.close();
$http.post(opt.unRegisterUrl, null, function(r) {});
}
var deregUI = $rootScope.$on('$stateChangeStart', function(){
stopHeartBeatAndUnregister();
deregUI();
});
var deregRouter = $rootScope.$on('$routeChangeStart', function(){
stopHeartBeatAndUnregister();
deregRouter();
});
}
}
}
}
var key = selector in handlers ? selector : (cmd in handlers ? cmd : false);
if (key)
{
$rootScope.$apply(function () {
handlers[key].apply(sse, [msg]);
});
}
});
}
};
}]);
@andyfensham
Copy link

Hi, saw this on one of the forums. How would I use this in my angular app.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment