문제

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

도움이 되었습니까?

해결책

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);
    });
}
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top