等到最后一个功能完成它的工作然后在angularjs

时间:2016-07-14 10:33:12

标签: javascript angularjs

我正在创建一个小应用程序,其中我有40个小部件,我正在循环并获取数据并重新绘制它。

    $scope.loopWiget = function(){
    for(var i=0; i < $scope.totalWidget.length; i++)
    {
     if($scope.totalWidget[i].widgetType == "chart"){
     $scope.fetchData($scope.totalWidget[i]);}
    if($scope.totalWidget[i].widgetType == "table"){
     $scope.fetchDataFortable($scope.totalWidget[i]);}
    }

     };

     $scope.fetchData = function(id){
    // fetching data and in response calling other function
    $http({
       method: 'POST',
       url: 'rest/dataset/metadata',
       type: 'json',
       headers:{'id':id}
     }).success(function(response){

    $scope.drawWid(response);
      }) 
     };
$scope.fetchDataFortable= function(id){
    // fetching data and in response calling other function
    $http({
       method: 'POST',
       url: 'rest/dataset/metaTabledata',
       type: 'json',
       headers:{'id':id}
     }).success(function(response){

    $scope.drawWidTable(response);
      }) 
     };
    $scope.drawWid = function(response){
      // All draw logic comes here
    };
$scope.drawWidTable= function(response){
      // All draw logic comes here
    };

$scope.totalWidget = [{'widgetId':'1','widgetType':'table'},{'widgetId':'2','widgetType':'chart'},{'widgetId':'3','widgetType':'maps'},{'widgetId':'4','widgetType':'chart'}];
    $scope.loopWiget();

现在我的循环不等待完成drawWid函数并再次调用fetchdata,因为我在第一个小部件中获取第二个小部件的数据。所以如何在循环中等待,直到绘制函数完成其代码,然后为下一个小部件调用fetchData函数。

2 个答案:

答案 0 :(得分:0)

由于这是一个异步请求,所以这是随机呈现数据的常见原因。对此可能的解决方案很少:

第一种方法:将数据存储在响应数组中,并在获取所有数据后,只调用draw函数逐个呈现小部件,或者在循环索引处呈现小部件。

 widgets.forEach((widget, index) => {
            return this.myService.getData(widget.entityProp)
                .then(res => {
                    this.drawWid(res, index);
                });
 });


    drawWid(res, index) {
        compute logic accroding to the index of data .
    }

第二种方法:您可以使用$ q.all()从所有请求中获取数据,然后再渲染它。

答案 1 :(得分:0)

您可以尝试以下代码:

var index = 0;
$scope.loopWiget = function(){
    if(!$scope.totalWidget[index]){
        return;
    }
  var id = $scope.totalWidget[index]['widgetId'];

  if($scope.totalWidget[index].widgetType == "chart"){
        $scope.fetchData(id);
      }
      if($scope.totalWidget[index].widgetType == "table"){
         $scope.fetchDataFortable(id);
      }
 };

$scope.fetchData = function(id){
     $http({
           method: 'POST',
           url: 'rest/dataset/metadata',
           type: 'json',
           headers:{'id':id}
        }).success(function(response){
                $scope.drawWid(response);
                index++;

        });
}
$scope.drawWid = function(response){
  // All draw logic comes here
  $scope.loopWiget();
};

$scope.totalWidget = [{'widgetId':'1','widgetType':'table'},{'widgetId':'2','widgetType':'chart'},{'widgetId':'3','widgetType':'maps'},{'widgetId':'4','widgetType':'chart'}];
$scope.loopWiget();
相关问题