我正在编写一个小型 Angular Web 应用程序,在加载数据时遇到了问题。我使用 Firebase 作为数据源,并发现 AngularFire 项目听起来不错。但是,我无法控制数据的显示方式。
首先,我尝试使用常规隐式同步:
angularFire(ref, $scope, 'items');
当我在 View 中使用模型 $items 时,它工作正常并且显示了所有数据。但是,当数据从 Firebase 数据源到达时,它的格式不符合 View 支持的方式,因此我需要在显示数据之前对数据进行一些额外的结构更改。问题是,我不知道数据何时完全加载。我尝试将 $watch 分配给 $items,但调用得太早了。
所以,我继续尝试使用 angularfireCollection 代替:
$scope.items = angularFireCollection(new Firebase(url), optionalCallbackOnInitialLoad);
文档不太清楚“OptionalCallbackOnInitialLoad”的作用以及调用时间,但尝试访问 $items 集合中的第一项将抛出错误(“Uncaught TypeError: Cannot read property '0' of未定义”)。
我尝试添加一个按钮,并在按钮的点击处理程序中记录了 $items 中第一个项目的内容,它有效:
console.log($scope.items[0]);
就在那里!我的 Firebase 中的第一个对象显示没有任何错误...唯一的问题是我必须单击一个按钮才能到达那里。
那么,有谁知道我如何知道何时加载所有数据,然后然后将其分配给 $scope 变量以显示在我的 View 中?或者还有其他办法吗?
我的 Controller :
app.controller('MyController', ['$scope', 'angularFireCollection',
function MyController($scope, angularFireCollection) {
$scope.start = function()
{
var ref = new Firebase('https://url.firebaseio.com/days');
console.log("start");
console.log("before load?");
$scope.items = angularFireCollection(ref, function()
{
console.log("loaded?");
console.log($scope.items[0]); //undefined
});
console.log("start() out");
};
$scope.start();
//wait for changes
$scope.$watch('items', function() {
console.log("items watch");
console.log($scope.items[0]); //undefined
});
$scope.testData = function()
{
console.log($scope.items[0].properties); //not undefined
};
}
]);
我的看法:
<button ng-click="testData()">Is the data loaded yet?</button>
提前致谢!
最佳答案
So, does anyone know how I can know when all the data has been loaded and then assign it to a $scope variable to be displayed in my view? Or is there another way?
请记住,所有 Firebase 调用都是异步的。许多问题的发生是因为您试图访问尚不存在的元素。按钮单击对您有效的原因是您在成功加载按钮(并访问元素)后单击了按钮。
对于optionalCallbackOnInitialLoad
,这是一个在angularFireCollection
初始加载完成后将执行的函数。顾名思义,它是可选的,这意味着如果您不想,则不必提供回调函数。
您可以使用它并指定加载后要执行的函数,也可以使用 $q
Promise 或您喜欢的其他 Promise 库。我偏爱kriskowal's Q我。我建议您阅读一些有关异步 JavaScript 的内容,以便您可以更深入地了解其中的一些问题。
请注意:
$scope.items = angularFireCollection(ref, function()
{
console.log("loaded?");
console.log($scope.items[0]); //undefined
});
确实正确指定了回调函数,但$scope.items
直到您运行回调之后才被分配。所以,它仍然不会存在。
如果您只想查看 $scope.items
何时加载,您可以尝试如下操作:
$scope.$watch('items', function (items) {
console.log(items)
});
关于angularjs - Angular 火集合 : know when the data is fully loaded,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18946064/