0

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

我有一个名为的控制器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]
4

2 回答 2

0

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

于 2015-11-09T11:29:35.713 回答
0

您需要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方法时

于 2015-07-11T06:54:18.580 回答