AngularJS:控制器将 Factory 的 $http 响应记录为 "undefined"

AngularJS: Controller logs Factory's $http response as "undefined"

我希望控制器可以使用我的 $http 响应数据,以便通过指令(“{{ hint }}”)在视图中显示 JSON 数据。然而,虽然在控制器中,我可以从工厂记录数据,但数据不会以可用的方式提供自身。

当工厂提供的内容被记录在控制器中时,它是"undefined"或"not a function"。从下面的代码中,记录了 "undefined""

求求你帮我改正错误好吗?我该如何清理它,以便在控制器中使用工厂的 .GET 数据?

控制器:

var MainCtrl = angular.module('MainCtrl', []);

MainCtrl.controller('Ctrl2', [ "QuizViewServ", '$log', '$scope',
function(QuizViewServ, $log, $scope){


 $scope.init = function(){
    $scope.hint = "FooBar";  //Testing binding bw Ctrl2 & the view
    $log.log(QuizViewServ.getQuizData.quizQz); // <-LOGS AS "UNDEFINED"
 }

}]);

工厂:

var MainServ = angular.module('MainServ', []);

MainServ.factory('QuizViewServ', ['$http', function($http){
 console.log("factory working");

 var getQuizData = function(){

   $http({
      method: 'GET',
      url: '/assets/json.json'
    }).then(function successCallback(response) {
        console.log("inside successgul GET req");


        var quizQz;
        quizQz = response.data.quizQs;
        console.log(quizQz);


    }, function errorCallback(response) {

        alert("Trouble grabbing requested data.")
    });
  }
  return {
    getQuizData : getQuizData
  }

}]);

$http 使用对 return 结果的承诺。使用 QuizViewServ.getQuizData.quizQz 时,您什么都不记录,因为它是异步的。

在你的工厂里,return 承诺,在你的控制器里,处理它。

var MainServ = angular.module('MainServ', []);

MainServ.factory('QuizViewServ', ['$http', function($http){
 console.log("factory working");

 var getQuizData = function(){

   return $http({
      method: 'GET',
      url: '/assets/json.json'
    })
  }
  return {
    getQuizData : getQuizData
  }

}]);

并在您的控制器中

var MainCtrl = angular.module('MainCtrl', []);

MainCtrl.controller('Ctrl2', [ "QuizViewServ", '$log', '$scope',
function(QuizViewServ, $log, $scope){


 $scope.init = function(){
    $scope.hint = "FooBar";  //Testing binding bw Ctrl2 & the view

    QuizViewServ.getQuizData().then(function(result){
        $log.log(result.data);
    });
 }

}]);

您需要重新运行该数据。这是不可能的,因为你正在做。 quizQz 属性也是私有的。即使在 ajax 调用后设置了该值,您也无法访问它。

var getQuizData = function(){

return $http({
  method: 'GET',
  url: '/assets/json.json'
}).then(function successCallback(response) {
    console.log("inside successgul GET req");


    var quizQz;
    quizQz = response.data.quizQs;
    console.log(quizQz);
    return quizQz;

  }, function errorCallback(response) {

    alert("Trouble grabbing requested data.")
    return '';
});

}

然后在控制器中,获取这样的数据。

QuizViewServ.getQuizData().then(function(data){
    console.log(data);
});