0

I am new to angularjs and trying to assign the data from http request function to $scope variable. but due to asynchronous, this line of code console.log($scope.field_result_var ) will be execute before it the request done

app.controller('my_control', function($scope, $http) {

        $scope.field_result_var  ='';       

        $scope.check_field_http = function() {
            $http({
                    method: 'GET',
                    url: 'aaa.php',
                    params : {field:$scope.field_data}
                    }).then(function successCallback(response) {
                            $scope.field_result_var  = response.data;

                     }, function errorCallback(response) {

                     });
        };


        $scope.check_field = function() {
            $scope.check_field_http ();

            //below is code need to execute after get the data like
            console.log($scope.field_result_var  );     
        };


});

I have tried to use callback function based on the answer in AngularJS http return value, but I might implement the callback function incorrectly, thus the console.log($scope.field_result_var ) still execute before it the request done

app.controller('my_control', function($scope, $http) {

        $scope.field_result_var  ='';       

        $scope.check_field_http = function() {
            $http({
                    method: 'GET',
                    url: 'aaa.php',
                    params : {field:$scope.field_data}
                    }).then(function successCallback(response) {
                            myCallbackFunction(response);

                     }, function errorCallback(response) {

                     });
        };


        $scope.check_field = function() {
            $scope.check_field_http ();

            //below is code need to execute after get the data like
            console.log($scope.field_result_var);       
        };

       function myCallbackFunction(response_param) {
            $scope.field_result_var  = response_param.data; 
        }
});

I am sorry that I have few question here, some might be general concept for angularjs:

1) What is the mistakes I made for the callback implementation to ensure the console.log will execute after the $http request success?

2) If I defined the callback function like, how to call it for my case?

 $scope.myCallbackFunction = function (response_param) {
            $scope.field_result_var  = response_param.data; 
        }

3) What is the difference between

  $scope.myCallbackFunction = function (response_param) {
            $scope.field_result_var  = response_param.data; 
        }

and

 function myCallbackFunction(response_param) {
            $scope.field_result_var  = response_param.data; 
        }

in angularjs?

4) When searching the solution, I saw people create http request inside myApp.factory like How to wait till the response comes from the $http request, in angularjs?

What is the difference between create a function with myApp.factory vs create a function using $scope.function_name = function()

Community
  • 1
  • 1
asdzxcyykk
  • 69
  • 2
  • 5

2 Answers2

2

You are asking a lot of things things all in this question. Let's start at the end and work backwards since you asked the high level questions at the bottom there.

What is the difference between create a function with myApp.factory vs create a function using $scope.function_name = function()

In AngularJS, there is a concept of services that are injectable blocks of code for encapsulating certain functionality. To make things a bit more confusing, there are specific types of services with their own syntax. You could use .factory(), .provider(), or .service(), but they all pretty much provide the same purpose of being a place to put business logic that you might otherwise put in the controller (and in Angular 2 they are all consolidated in just "services").

4) When searching the solution, I saw people create http request inside myApp.factory like How to wait till the response comes from the $http request, in angularjs?

The responsibility of your main component (or controller) should be holding the data so that the view can display it. Calling out to an http request is not something that should be in your controller because then it becomes large and bloated. As a general rule of thumb: Keep your controllers as thin as possible, making use of "helper" services that provide one main service.

3) What is the difference between

$scope.myCallbackFunction = function (response_param) { $scope.field_result_var = response_param.data; } and

function myCallbackFunction(response_param) { $scope.field_result_var = response_param.data; } in angularjs?

The concept you are asking about here is anonymous functions which are not at all unique to AngularJS or even JavaScript for that matter. An anonymous function does not have a name. These are very common in JavaScript development, especially for callbacks of asynchronous operations. To the computer interpreting the code there is no difference, but the anonymous function uses less characters, less lines, and you don't need to jump around to find your callback function. As a general rule of thumb: If you never actually call the function by name, consider making it anonymous.

2) If I defined the callback function like, how to call it for my case?

$scope.myCallbackFunction = function (response_param) { $scope.field_result_var = response_param.data; }

You have defined the function as the value for a variable named $scope.myCallbackFunction. So you can then you can just do this:

    $scope.check_field_http = function() {
        $http({
            method: 'GET',
            url: 'aaa.php',
            params : {field:$scope.field_data}
            }).then(
                 $scope.myCallbackFunction, 
                 $scope.myCallbackFunction
            );
        };

Now, to answer you original question, "What is the mistake here?". It seems that the console.log statement occurs inside of the $scope.check_field function. Async requests are non blocking in JavaScript so $scope.check_field_http will run, sending off its request. Then the interpreter will continue to step through the code, executing the log statement immediately after the request is sent but without waiting for a response to come back. If you want the console.log statement to occur after the request comes back then you should move it into the body of the function named myCallbackFunction.

Jim
  • 3,821
  • 1
  • 28
  • 60
  • Thanks for the explanation, if I insist to call console.log in $scope.check_field, can I achieve it using return promise like http://stackoverflow.com/questions/18421830/how-to-wait-till-the-response-comes-from-the-http-request-in-angularjs . – asdzxcyykk Jan 04 '17 at 04:54
  • Yes, you could have a promise in $scope.check_field and then resolve it in the success callback. – Jim Jan 05 '17 at 03:03
0

maybe you should use .success instead of .then in your http request, and you can also user .error to handle errors in your http request

something like this

$http({ url: url, method: method, }).success(function (data, status, headers, config) { //your success logic here }) .error(function (data, status, headers, config) { //your error logic here }) .finally(function () { //your finally logic here (optional) });
Nonik
  • 645
  • 4
  • 11
  • About v1.5 or 1.6, `success` and `error` were deprecated. Use something like `$http.get(url).then(Self.ProcessSearchResults).catch(Self.SearchFailed);` (copied directly from my working code; sorry, but I am too busy to update this. Note that any response except 200 will trigger the `catch`. No offence, this was a great answer when posted; I just don't want anyone copying it now - if anyone is still suing AngualrJs, that is :-) – Mawg says reinstate Monica Apr 11 '21 at 21:12