加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > 安全 > 正文

angularjs – angularfireCollection:知道数据何时完全加载

发布时间:2020-12-17 10:21:37 所属栏目:安全 来源:网络整理
导读:我正在编写一个小的Angular Web应用程序,并且在加载数据时遇到了问题.我使用Firebase作为数据源,发现AngularFire项目听起来不错.但是,我无法控制数据的显示方式. 起初我尝试使用常规隐式同步: angularFire(ref,$scope,'items'); 它工作正常,当我在视图中使
我正在编写一个小的Angular Web应用程序,并且在加载数据时遇到了问题.我使用Firebase作为数据源,发现AngularFire项目听起来不错.但是,我无法控制数据的显示方式.

起初我尝试使用常规隐式同步:

angularFire(ref,$scope,'items');

它工作正常,当我在视图中使用模型$items时显示所有数据.但是,当数据从Firebase数据源到达时,它的格式不会以视图支持的方式进行格式化,因此我需要在数据显示之前对数据进行一些额外的结构更改.问题是,我不知道数据何时完全加载.我尝试为$items分配一个$watch,但它被称为太早了.

所以,我继续前进并尝试使用angularfireCollection:

$scope.items = angularFireCollection(new Firebase(url),optionalCallbackOnInitialLoad);

文档不是很清楚“optionalCallbackOnInitialLoad”的作用以及何时调用它,但是尝试访问$items集合中的第一项将引发错误(“Uncaught TypeError:无法读取未定义的属性’0’”) .

我尝试添加一个按钮,在按钮的单击处理程序中,我记录了$items中第一项的内容,并且它有效:

console.log($scope.items[0]);

那是它!我的Firebase中的第一个对象显示没有任何错误…唯一的问题是我必须单击按钮才能到达那里.

那么,有没有人知道我怎么知道何时加载了所有数据然后将它分配给$scope变量以显示在我的视图中?或者还有另一种方式吗?

我的控制器:

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 promises或你喜欢的另一个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)
});

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读