Reputation: 113
I'm building an app that needs to detect when a user loses internet connectivity or cannot reach the server. Multiple controllers and services need to be able to check and set this. I have achieved all of this with no problem using an angular service and
window.addEventListener('offline', function() {OfflineService.checkIfOnline});
then in the service with something like
window.navigator.onLine ? online = true : online = false
The tricky part comes in when I need to update the view when the offline event occurs. I can't seem to find a way to update the scope property or a controller property when the service property gets updated by the event.
When I use $scope.$watch, the function fires 10 times (noted by console.log) and then never again.
I tried to replicate the problem in a jsfiddle, but this is my first time using that tool, and I'm not sure if I did it right:
https://jsfiddle.net/m3nx5yLm/1/
Thank you for your help.
Upvotes: 0
Views: 133
Reputation: 113
Thank you everyone for your help.
I ended up going with a solution suggested by a buddy of mine. Using $rootScope.$emit('offlineEvent' true);
in the service and listening for it in the controller with $rootScope.$on('offlineEvent' this.setControllerProperty);
.
Upvotes: 1
Reputation: 19748
https://jsfiddle.net/m3nx5yLm/3/
constructor($scope, OfflineNotificationService){
Looks like you were referencing the class from the scope not the instance created by the injector (needed to pass it in along with $scope). I also used the watch syntax where the first arg is a function just to be clear about making that call, the string syntax is typically just used to reference properties on scope. A few other notes you can just return the window.navigator.onLine and you can store the value on the service instance and reference it directly from the view, you can then call checkOnline periodically with a $timeout loop or listening for the online/offline events on the browser instead of using the watch to fire the function.
https://jsfiddle.net/m3nx5yLm/4/
Upvotes: 0