How to work with the $http service of Angularjs synchronously?

Asked

Viewed 201 times

1

How to work with Angularjs $http service synchronously?

In this case I’m using Angularjs + Laravel and 3 tables to save a questionnaire (where an evaluation has several questions, and each question has several items):

  • avaliations (id, user_id, project_id, processed);

  • avaliation_questions (id, avaliation_id, question_id, Average, Obs);

  • avaliation_question_items (id, avaliation_question_id, question_item_id, value);

Note: the backend (Laravel) works perfectly in separate tests, but when I put $http.post inside the for does not save all the items of the questions and not all questions... and there returns several times the error:

POST http://localhost:8000/teste/api/avaliation_question/create 
XMLHttpRequest cannot load http://localhost:8000/teste/api/avaliation_question/create. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://teste.localhost' is therefore not allowed access. The response had HTTP status code 401.

My code (excerpt from the controller where you have the $http.post):

$scope.save = function () {

    // table avaliations
    $scope.avaliations.user_id = $scope.currentUser.id;
    $scope.avaliations.user_valuer_id = $scope.valuer.id;
    $scope.avaliations.project_id = $scope.project.id;
    $scope.avaliations.processed = 0;
    $scope.avaliations.send = 0;

    // begin save avaliations ----------------------------------------------
    $http.post(ApiUrl.api_url + "/api/avaliation/create", $scope.avaliations).
    success(function (data, status) {
        if (status == 200) {

            // coloca o id da questao e o id da avaliacao
            for (var question in $scope.avaliation_questions) {
                $scope.avaliation_questions[question].avaliation_id = data.id;
                $scope.avaliation_questions[question].question_id = question;

                // begin save avaliation_questions -------------------------
                $http.post(ApiUrl.api_url + "/api/avaliation_question/create", $scope.avaliation_questions[question]).
                success(function (data, status) {
                    if (status == 200) {

                        // coloca o id do item do questionario
                        for (var item in $scope.avaliation_question_items[question]) {
                            $scope.avaliation_question_items[question][item].avaliation_question_id = data.id;
                            $scope.avaliation_question_items[question][item].question_items_id = item;

                            // begin save avaliation_question_items --------
                            $http.post(ApiUrl.api_url + "/api/avaliation_question_item/create", $scope.avaliation_question_items[question][item]).
                            success(function (data, status) {
                                if (status == 200) {

                                    $scope.toaster = {
                                        type: 'success',
                                        title: 'Avaliação',
                                        text: 'Avaliação salva com sucesso!'
                                    };
                                    toaster.pop($scope.toaster.type, $scope.toaster.title, $scope.toaster.text);

                                } else {

                                    $scope.toaster = {
                                        type: 'error',
                                        title: 'Itens da questão',
                                        text: 'Erro encontrado ao salvar este item: status - ' + status
                                    };
                                    toaster.pop($scope.toaster.type, $scope.toaster.title, $scope.toaster.text);

                                }
                            }).
                            error(function (data, status) {
                                $scope.toaster = {
                                    type: 'error',
                                    title: 'Itens da questão',
                                    text: 'Erro de sistema'
                                };
                                toaster.pop($scope.toaster.type, $scope.toaster.title, $scope.toaster.text);
                            });
                            // end save avaliation_question_items ----------

                        }

                    } else {

                        $scope.toaster = {
                            type: 'error',
                            title: 'Questões da avaliação',
                            text: 'Erro encontrado ao salvar esta questão: status - ' + status
                        };
                        toaster.pop($scope.toaster.type, $scope.toaster.title, $scope.toaster.text);

                    }
                }).
                error(function (data, status) {
                    $scope.toaster = {
                        type: 'error',
                        title: 'Questões da avaliação',
                        text: 'Erro de sistema'
                    };
                    toaster.pop($scope.toaster.type, $scope.toaster.title, $scope.toaster.text);
                });
                // end save avaliation_questions ---------------------------
            }

        } else {

            $scope.toaster = {
                type: 'error',
                title: 'Avaliação',
                text: 'Erro encontrado ao salvar esta avaliação: status - ' + status
            };
            toaster.pop($scope.toaster.type, $scope.toaster.title, $scope.toaster.text);

        }
    }).
    error(function (data, status) {
        $scope.toaster = {
            type: 'error',
            title: 'Avaliação',
            text: 'Erro de sistema'
        };
        toaster.pop($scope.toaster.type, $scope.toaster.title, $scope.toaster.text);
    });
    // end save avaliations ------------------------------------------------
};

1 answer

0

Unfortunately the Angular does not have a helper for requests síncronas, if you consult the source code of the angular directly I its repository consulting line 77 you can verify that in the opening of the XHR object, in the third parameter is specified a true which specifies that the query will be asíncrona while you would need this to be as false.

Reference of line 77:

xhr.open(method, url, true);

To solve your problem the solution is to make the request in hand and assign the values to your scope, follows an example of how to create synchronous requests natively.


Reference: SOEN

  • I would say "Fortunately", since synchronous requests in ajax are with the days contacts.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.