how to make synchronous http request in angular js

前端 未结 3 1779
北海茫月
北海茫月 2020-12-03 10:27

How to make blocking http request in AngularJS so that i can use the $http response on very next line?

In the following example, $http object doesn\'t

3条回答
  •  甜味超标
    2020-12-03 11:02

    Here is a practical answer, courtesy of user Kirill Slatin who posted the answer as a comment. Practical use example at the bottom of the answer.

    If, like me, you need to use that response object as a scope variable, this should work:

    $http.get('URL').success(function(data){
    
    $scope.data = data;
    $.fullCalender = $scope.data;
    $scope.$apply()
    });
    

    $scope.$apply() is what will persist the response object so you can use that data.

    -

    Why would you need to do this?

    I'd been trying to create an "edit" page for my recipes app. I needed to populate my form with the selected recipe's data. After making my GET request, and passing the response data to the $scope.form, I got nothing... $scope.$apply() and Kirill Slatin helped big time. Cheers mate!

    Here's the example from my editRecipeController:

      $http.get('api/recipe/' + currentRecipeId).then(
        function (data) {
          $scope.recipe = data.data;
          $scope.form = $scope.recipe;
          $scope.$apply()
        }
    );
    

    Hope that helps!

提交回复
热议问题