问题
I am using AngularFire and promises on arrays ($loaded()
on firebaseArray()
).
Currently, I'm using the following code:
Problem: I go to page1, the data is loaded and all fine. Go to page 2 and come back to page1. Now the $loaded()
doesn't work until I do a full page refresh. How do I fix this problem?
app.factory('Items', ['FBURL', '$firebaseArray', function(FBURL, $firebaseArray) {
return {
ofCategory: function(catId){
var ref = new Firebase(FBURL);
var refSearch = new Firebase.util.NormalizedCollection(...).select(...).ref();
var allItems= refSearch.orderByChild(...);
return $firebaseArray(allItems);
}
};
}]);
Page1:
function readData() {
if($scope.Items) {
$scope.Items.$destroy();
$scope.Items= null;
}
$scope.Items = Items.ofCategory($routeParams.id);
$scope.Items.$loaded().then(function(itm) {
...
});
}
Page2:
$scope.Items= Items.ofCategory($routeParams.id);
The Firebase documentation1 says: "$loaded()
returns a promise which resolves after the initial records have been downloaded from our database. This is only called once and should be used with care", and that is probably what I get here.
What I've tried: As shown, in my readData()
function on Page1, I destroy the $scope.Items
variable before any new load. But it doesn't seem to be doing anything. AFAIU, $loaded()
is working on firebaseArray()
, so destroying the $scope
array might not help much. So, what else should I do to make this work without needing to fully refresh the page?
回答1:
I have heard that AngularFire should be avoided and this looks like a good reason.
Use the firebase API directly:
app.factory('FbItems', ['FBURL', '$q', function(FBURL, $q) {
return {
ofCategory: function(catId){
var ref = new Firebase(FBURL);
var refSearch = new Firebase.util.NormalizedCollection(...).select(...).ref();
var allItems= refSearch.orderByChild(...);
var promise = allItems.once('value').then(function(snapshot) {
return snapshot.val();
});
return $q.when(promise);
}
};
}]);
It is important to convert the ES6 promise to an AngularJS $q promise with $q.when. Only operations which are applied in the AngularJS execution context will benefit from AngularJS data-binding, exception handling, property watching, etc.
Usage:
function readData() {
promise = FbItems.ofCategory($routeParams.id);
promise.then(function(items) {
$scope.Items = items;
}).catch(function(error) {
console.log(error);
});
}
来源:https://stackoverflow.com/questions/50738504/angularfire-v1-2-firebasearray-loaded-only-called-once