I've been working on a webapp where I have to receive messages on a websocket and make changes.
So basically, I have something like:
var socketService = angular.module('socketService');
socketService.factory('Listen', function () {
// connect etc.
socket.onmessage = function (msg) {
lastMsg = msg;
console.log(msg); // this is instant
}
return {
lastMsg: function () {
return lastMsg;
}
}
});
And I've got another module I'm using this service in, inside a controller
var mainMod = angular.module('mainMod', ['socketService']);
// some more stuff
mainMod.controller('MainCtrl', function(Listen) {
$scope.$watch(Listen.lastMsg, function (newmsg, oldmsg) { // this is laggy
// do stuff here
});
});
The issue is this: my $watch
doesn't trigger as soon as there's a message received on the socket. If I console.log
all the socket messages in the service, the logs appear instantly, but $watch takes its own sweet time to trigger. Also, it's quite irregular – I don't see a pattern in the lags.
I'm thinking this has to do with Angular's ticks – and the $watch compares on every tick, but that severely affects my app's performance.
One possible workaround is to use $broadcast
, but I don't want that approach.
What should I do here?