【问题标题】:How to the objects to perform calculation in angularjs如何在angularjs中执行计算的对象
【发布时间】:2017-09-22 06:10:08
【问题描述】:

我在我的项目中使用 angularjs。

我能够从数据库中获取记录并绑定到 html 页面中。这里我需要从数据库中的 4 个集合中获取数据,因此我需要执行多个服务器调用来获取数据。当我在单独的 Scope 变量中分配所有内容时。我的示例代码如下

var click = function(){    
     $http.get('/CalBuildingget').then(function (response) {                    
                    $scope.ViewBuildings = response.data;

                    });

     for (i = 0; i < $scope.ViewBuildings.length; i++) {
        $http.get('/CalBuildingFloorget/'+ scope.ViewManageBuildings[i]._id).then(function (response) {                                
                    $scope.floorDetails = response.data;        
                        });
                     }

在这里,我需要通过其 ID 获取每个建筑物的楼层并将其作为数组对象存储在建筑物范围中,然后通过楼层 ID 再次获取单元,这些单元再次需要执行服务器调用并在范围内分配。

我怎样才能做到这一点,因为它首先执行循环,然后开始构建服务器调用。

【问题讨论】:

    标签: javascript angularjs arrays node.js mongodb


    【解决方案1】:

    您需要在第一个请求的成功回调中获取楼层。 所以像这样。

    var click = function(){    
     $http.get('/CalBuildingget').then(function (response) {                    
                    $scope.ViewBuildings = response.data;
                    for (i = 0; i < $scope.ViewBuildings.length; i++) {
                      $http.get('/CalBuildingFloorget/'+  scope.ViewManageBuildings[i]._id).then(function (response) {                                
                    $scope.floorDetails = response.data;        
                        });
                     }
                    });
    

    【讨论】:

      【解决方案2】:

      您使用的方法会破坏应用程序的整体性能,您确定要循环发送 HTTP 调用吗?想一想当你有大约 1000 条记录的情况下,你能负担得起向服务器发送 1000 次 HTTP 调用吗?相反,你为什么不在 /CalBuildingget/ 中获取 floorDetails 呢?

      切勿循环发送 HTTP 调用,考虑网络带宽和应用程序性能。

      【讨论】:

        【解决方案3】:

        对于多个后续服务调用,您应该始终使用承诺概念。从概念上讲,它应该如下所示:

        function callServiceForEachItem() {
          var promise;
        
          angular.forEach(items, function(item) {
            if (!promise) {
              //First time through so just call the service
              promise = fakeService.doSomething(item);
            } else {
              //Chain each subsequent request
              promise = promise.then(function() {
        
                return fakeService.doSomething(item);
              });
            }
          });
        }
        

        使用此链接获取最佳实践perform chain service call

        你可以查看this讨论

        【讨论】:

          猜你喜欢
          • 2019-09-26
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2021-04-02
          • 1970-01-01
          • 2016-09-17
          • 1970-01-01
          • 2010-10-11
          相关资源
          最近更新 更多