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 基于卷积神经网络的声纹识别
  • ¥15 Python中的request,如何使用ssr节点,通过代理requests网页。本人在泰国,需要用大陆ip才能玩网页游戏,合法合规。
  • ¥100 为什么这个恒流源电路不能恒流?
  • ¥15 有偿求跨组件数据流路径图
  • ¥15 写一个方法checkPerson,入参实体类Person,出参布尔值
  • ¥15 我想咨询一下路面纹理三维点云数据处理的一些问题,上传的坐标文件里是怎么对无序点进行编号的,以及xy坐标在处理的时候是进行整体模型分片处理的吗
  • ¥15 CSAPPattacklab
  • ¥15 一直显示正在等待HID—ISP
  • ¥15 Python turtle 画图
  • ¥15 stm32开发clion时遇到的编译问题