在angularJS中合并来自一个服务的两个数组

merging two arrays from a service in angularJS

本文关键字:一个 服务 数组 两个 angularJS 合并      更新时间:2023-09-26

我在合并来自web服务的数据时遇到了一个问题,该服务发送表中所选行的id,并使用该id获取数据,这是我在控制台中获得的:

my all Liste [{ I get only the data of finalOperationsList not with the $scope.liste data}]

这是我的代码:

.factory('gammeMonatageFactory', function($http,$q){
     var backObject = { getListOperationsById:_getListOperationsById }
     return backObject;
     function _getListOperationsById(val){            
              var defer = $q.defer();
              $http({
                  method : "GET",
                  url : "MyURL/getById:"+val
              }).then(function mySucces(response) {
                  defer.resolve(response.data);
              }, function myError(response) {
                  deferred.reject('Erreur into url '+response);
              });  
              return defer.promise;
     };        
});

这就是我所称的服务:

$scope.modifierOuCreerArticle = function() {    
     var v = $scope.OperationsList[$scope.OperationsList.length-1].Id;
     gammeMonatageFactory.getListOperationsById(v).then(function(Data){
         $scope.liste= JSON.parse(JSON.stringify(Data));  
         //I get the Data of $scope.liste only here I can't get this Data     outside this call                            
     });
     $scope.listfinal = $scope.finalOperationsList.concat($scope.liste);
     console.log("my all Liste "+$listfinal);
 }

请帮助合并2个finalOperationsListliste阵列感谢的帮助

合并两个数组时,rest调用的回调尚未执行。因此,当设置了liste数据时,您应该在回调中合并这两个列表。您可以使用空数组或一些初始数据初始化$scope.listfinal。视图将随之更新。

$scope.modifierOuCreerArticle = function() {    
     var v = $scope.OperationsList[$scope.OperationsList.length-1].Id;
     gammeMonatageFactory.getListOperationsById(v).then(function(Data){
         $scope.liste = JSON.parse(JSON.stringify(Data));  
         $scope.listfinal = $scope.finalOperationsList.concat($scope.liste); // concat the arrays when $scope.liste is available                         
     });
     $scope.listfinal = $scope.finalOperationsList; // or initialize the list with empty array;
     console.log("my all Liste " + $listfinal);
 }

我从您的代码中看到的另一件事是,您的service存在针对promise反模式的问题

在服务内部,最好是:

function _getListOperationsById(val){ 
      //instead of create your own promise object, chaining the promise object returned by $http and return it
      return $http({
          method : "GET",
          url : "MyURL/getById:"+val
      }).then(function mySucces(response) {
          return response.data;
      }, function myError(response) {
          return $q.reject('Erreur into url '+response);
      });  
  };

如果您不需要将服务中的响应作为中间层处理,我建议直接返回结果:

function _getListOperationsById(val){ 
      //instead of create your own promise object, chaining the promise object returned by $http and return it
      return $http({
          method : "GET",
          url : "MyURL/getById:"+val
      });  
  };

并且其他人已经给出了解决方案,您应该在返回的promise then()函数中将它们合并在一起。