Reputation: 2384
So I have a controller to load all the tasks for example:
$scope.tasks = taskService.all;
$scope.tasks.$loaded().then(function(data){
console.log (data);
});
//--------Destroy all the AngularFire connection------//
$scope.$on("$destroy", function(){
$scope.tasks.$destroy();
});
The taskService is as below:
var ref = new Firebase(FirebaseUrl);
var tasks = $firebaseArray(ref.child('tasks'));
var uid = Users.LoginUserId();
var Task = {
all: tasks,
getAllTasks: function() {
console.log ("Run get All tasks.");
return $firebaseArray(ref.child('tasks'));
},
... ...
...
Use $scope.tasks = taskService.all; I think I am getting a tasks array - which is ONE firebaseArray. When I logout using Auth.$unauth(), there is no permission errors. When I log back in and go to the same view, $scope.tasks is a empty array = []. I don't know why the taskService don't go get the tasks firebaseArray again. It will only go get the firebase array when I force refresh the browser.
If I use
$scope.tasks = taskService.getAllTasks();
in the taskService - a method / function to return firebaseArray. This tasks will not be empty array after I logout and log back in. But I can tell when I logout, there are many permission errors - look like there are many firebaseArray(s) each time I come to this view (waste of resources since there are multiple same copy of tasks array?!?)
So which is the right way to handle it? Why using a method in services/factory will produce multiple duplicated firebaseAarray when I navigate around my app and back to the same views? Is that really bad? And why using a factory.value way will cause issue when logout and log back in? I can not find any clear explanation about this. Firebase expert please help.
EDIT FOR FINIAL SOLUTION:
Thanks to @nicolas here is my finial solution: The code provided by nicolas can't work on my solution since this.$$tasks = [] will still be true. It is not NULL. It is just an empty array. So I have to do this instead:
getAllTasks: function() {
if (tasks.length == 0) {
console.log ("Logout and Log back in. Tasks is empty!");
tasks = $firebaseArray(ref.child('tasks'));
} else {
console.log ("Navigate around. Tasks is NOT empty!");
tasks = tasks;
}
return tasks;
},
tasks is already inside a factory and it is private. I don't think I need to use $$.
Upvotes: 1
Views: 738
Reputation: 920
when you logout you should basically call $destroy on all your angularfire instances, because each of them keep some socket open. So if you have set up some security rules based on your current user id and you log out , you may break them and get exceptions.
Refering to your task service , i would cache the array once instanciated (since firebase will automatically sync it), and listen to child_added events.
var Task = {
getAllTasks: function() {
this.$$tasks = (this.$$tasks || firebaseArray(ref.child('tasks')));
return this.$$tasks;
}
Upvotes: 3