如何等待AngularJS中的数据加载?

时间:2015-11-02 20:44:12

标签: javascript angularjs

在我的应用程序中,我有一些数据,我从服务中获取,然后我继续在我的代码中使用来预加载表单。但是,有时在运行其余代码之后,数据才会被加载,因此表单将显示为空白。其他时候,它很好,一切都加载。我想这样做,它总是加载表格填充所有字段。

问题是我有多个服务调用,那么如何确保所有服务都已完成加载?这是我的代码:

在参考数据服务中(其余的GET几乎使用相同类型的代码):

   var lines = d3.select("svg").selectAll(".myLine")
        .data(allLines)

    lines.enter()
        .append("path")
        .attr("class", "myLine")
        .attr("d", tweetLine)
        .attr("fill", "none")
        .attr("stroke", "darkred")
        .attr("stroke-width", 2)

    lines.exit().remove();

    lines.attr("class", "myLine")
        .attr("d", tweetLine)
        .attr("fill", "none")
        .attr("stroke", "darkred")
        .attr("stroke-width", 2)

在控制器中:

        factory.getAllOffices= function(){
          var deferred = $q.defer();
          $http.get(APP_CONFIG.refURL+"/reference/getAllOffices")
            .success(function(response){
                deferred.resolve(response);
            })
            .error(function(msg, code, headers, config){
                console.log(msg);
                deferred.reject(msg);
            });
        return deferred.promise;
    };

有时,在运行formID代码之前,不会返回办公室,类型和团队。

1 个答案:

答案 0 :(得分:4)

您可以使用q.all(),因为它接受一系列承诺,只有在所有承诺都已解决后才能解决。

$q.all([
      referenceDataService.getAllTypes(),
      referenceDataService.getAllTeams()
    ]).then(function(data){
      $scope.allTypes = data[0];
      $scope.teamOptions.data = data[1];
 });

您还可以选择使用ng-hide/ng-show显示/隐藏某些元素的时间。您可以使用$scope.showProperty = false;初始化网页,一旦您的服务电话已解决,请将其切换为:$scope.showProperty = true;

相关问题