duanpo2813 2014-03-27 23:37
浏览 33
已采纳

变量未被返回(未识别) - AngularJS [重复]

This question already has an answer here:

In my controller I am calling the function

function initialiseQuizContent(quizIdArray){
   alert(getQuizService.getQuizContent(quizIdArray));
}

which calls the a method in the following service

app.service('getQuizService', function($http) {

    var quizArray;

    this.setQuizArray = function(quiz){
        quizArray = quiz;
    };

   this.getQuizArray = function(){
        return quizArray;
    };

    this.getQuizContent = function(quizArray){

        var $promise=$http.get("http://localhost/PHP/getQuizContent.php", {'quizArray': quizArray}); //send data to addQuiz.php
        var theReturn;
        $promise.then(function(msg){

            //alert(msg.data);
            theReturn = msg.data;
        });

        return theReturn;

    };

});

However the result I get for the alert is 'undefined'. I know that the call to the PHP file works fine as if I put 'alert(msg.data)' within the promise, as commented out above, then the correct array is returned. I am new to this so excuse any silly questions but it seems as if the value that is being returned for the 'getQuizContent()' method is done before the PHP file is executed and the msg.data is received? Resulting in the undefined variable 'theResult'.

I would appreciate any help. Thanks

</div>
  • 写回答

1条回答 默认 最新

  • douliang2167 2014-03-27 23:51
    关注

    Working with $http service means working with AJAX, the response is asynchronous, that why you got undefined, I would suggest changing your service and doing something like this:

    app.service('getQuizService', function($http) {
    
        var quizArray;
    
        this.setQuizArray = function(quiz){
            quizArray = quiz;
        };
    
       this.getQuizArray = function(){
            return quizArray;
        };
    
        this.getQuizContent = function(quizArray){
    
            var promise=$http.post("http://localhost/PHP/getQuizContent.php",
             {'quizArray': quizArray}).then(function (response) {
    
            console.log(response);
    
            return response.data;
          });
    
            return promise;
    
        };});
    

    then in controller do something like this:

    function initialiseQuizContent(quizIdArray){
         getQuizService.getQuizContent(quizIdArray).then(function(data){
         alert(data);
        });
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 教务系统账号被盗号如何追溯设备
  • ¥20 delta降尺度方法,未来数据怎么降尺度
  • ¥15 c# 使用NPOI快速将datatable数据导入excel中指定sheet,要求快速高效
  • ¥15 再不同版本的系统上,TCP传输速度不一致
  • ¥15 高德地图点聚合中Marker的位置无法实时更新
  • ¥15 DIFY API Endpoint 问题。
  • ¥20 sub地址DHCP问题
  • ¥15 delta降尺度计算的一些细节,有偿
  • ¥15 Arduino红外遥控代码有问题
  • ¥15 数值计算离散正交多项式