使用 angularjs 在 html 中加载异步解析数据

Loading asynchronous parse data inside html using angularjs

我正在尝试快速测试以调试为什么我的某些代码没有按预期工作。

我有一个名为 testCtrl 的控制器和一个名为 myService 的服务。在服务中,我试图从 Parse 获取数据,一旦我有了数据,我就试图将这些数据加载到我的前端 html.

代码如下:

app.controller('testCtrl', function($scope,myService) {
var currentUser = Parse.User.current();

$scope.username = currentUser.getUsername();
$scope.test = "ths";
var promise1 = myService.getEvaluatorData();
promise1.then(function(response){
    $scope.results2 = response;
    console.log(response);
    });
});

app.factory('myService', function(){
 return {
   getAllData: function($scope){
      getEvaluatorData($scope);
   },

   getEvaluatorData: function(){

       var evaluators = Parse.Object.extend("Evaluators");
       query = new Parse.Query(evaluators);

       return query.find({
          success: function(results){
            angular.forEach(results, function(res){

                console.log("Looped"); //this is just to verify that the then call below is executed only after all array objects are looped over.
            });

          } ,
          error: function(error){

          }
       });
   }
  }
});

这是我要显示数据的 html 代码:

<!DOCTYPE html>
<html>
<head lang="en">
    <meta charset="UTF-8">
    <title></title>
</head>
<body ng-controller="testCtrl">
{{test}}

{{results2}}
</body>
</html>

results2 没有加载到 html。

这是控制台日志。

testParse.js:46 This is done
2015-07-10 15:28:32.539testParse.js:46 This is done
2015-07-10 15:28:32.540testParse.js:46 This is done
2015-07-10 15:28:32.541testParse.js:46 This is done
2015-07-10 15:28:32.542testParse.js:56 Returning result as promised [object Object],[object Object],[object Object],[object Object]

您需要 return 来自您服务的数据并将其传递给您的控制器。例如:

app.controller('testCtrl', function ($scope, myService) {
    var currentUser = Parse.User.current();
    $scope.username = currentUser.getUsername();
    $scope.test = "this";
    myService.getEvaluatorData().then(function (response) {
        console.log('response', response);
        $scope.results2 = response;
    });
});

app.factory('myService', function ($http, $q) {
    return {
        getEvaluatorData: function () {
            var evaluators = Parse.Object.extend("Evaluators");
            var query = new Parse.Query(evaluators);

            return query.find({
                success: function (results) {
                    return results;
                },
                error: function (error) {
                   return error;
                }
            });
        }
    }
});

此外,在我看来调用 this.getEvaluatorData($scope) 没有意义,当您可以直接调用 getEvaluatorData 方法时

使用 $rootScope.result2 而不是 $scope.result2