Firebase and AngularJS Callbacks

I am learning AngularJS with Firebase. I am really struggling with the on Firebase callback and trying to update $scope ...

 $apply already in progress <---- var chat = angular.module('chat', []); chat.factory('firebaseService', function ($rootScope) { var firebase = {}; firebase = new Firebase("http://gamma.firebase.com/myUser"); return { on: function (eventName, callback) { firebase.on(eventName, function () { var args = arguments; $rootScope.$apply(function () { callback.apply(firebase, args); }); }); }, add: function (data) { firebase.set(data); } }; }); chat.controller ('chat', function ($scope, firebaseService) { $scope.messages = []; $scope.username; $scope.usermessage; firebaseService.on("child_added",function(data){ $scope.messages.push(data.val()); }); $scope.PushMessage = function(){ firebaseService.add({'username':$scope.username,'usermessage':$scope.usermessage}); }; }); 

If I $rootscope.$apply , then it works as expected, but it does not update the DOM when the page loads.

Thanks!

UPDATE

Solution 1 - Extract $rootscope.$apply in the service and enter and apply $timeout to the controller:

 firebaseService.on('child_added',function(data){ $timeout(function(){ $scope.messages.push(data.val()); },0); }); 

Solution 2 - Implement the SafeApply method (thanks to Alex Vanston ):

 $scope.safeApply = function(fn) { var phase = this.$root.$$phase; if(phase == '$apply' || phase == '$digest') { fn(); } else { this.$apply(fn); } }; 

Although both of these work and are not very coded, I feel that they are too hacks. Isn't there any official Angular way to handle Async callbacks?

Another great example I found for a similar situation: HTML5Rocks - AngularJS and Socket.io

+4
source share
1 answer

Solution 1 - Remove $ anchocop. $ apply to the service and add $ timeout to the controller:

 firebaseService.on('child_added',function(data){ $timeout(function(){ $scope.messages.push(data.val()); },0); }); 

Solution 2 - Implement the SafeApply method (thanks to Alex Vanston):

 $scope.safeApply = function(fn) { var phase = this.$root.$$phase; if(phase == '$apply' || phase == '$digest') { fn(); } else { this.$apply(fn); } }; 
+8
source

Source: https://habr.com/ru/post/1442004/


All Articles