-3

How to display reponse data (get) from server in AngularJS

in my code I need to alert $scope.orders inside that controller but it willll not show..

function OrderController($scope,$http)
{
    var orderPromise = $http.get("../api/order");

    orderPromise.success(function(data, status, headers, config) 
    {
        $scope.orders=data
        alert(JSON.stringify($scope.orders))  // First alert 
    });

    orderPromise.error(function(data, status, headers, config) 
    {
        alert("Error");

    });

    alert(JSON.stringify($scope.orders))    // Second alert 
}

How can i access $scope.orders to outside the success fun() Here I am alerting $scope.data in two times In here First Alert is shown but Second Alert is nothing to show why? How to show second one?

symon kt1
  • 45
  • 2
  • 11
  • 1
    Possible duplicate of [AngularJS : Scope issue in $http success callback](http://stackoverflow.com/questions/25043534/angularjs-scope-issue-in-http-success-callback) – Matheno Feb 09 '16 at 15:05
  • The reason the first alert works but the second one does not is because the execution of the first is delayed until the promise is successfully fulfilled... that can take anywhere from milliseconds to seconds, depending on the request. However, the second one is executed almost immediately after the controller is instantiated since it is run right after the promise handlers are defined (not executed). What exactly are you trying to do with the data? If you just want to display it, then bind the $scope.orders in you view, and it will automatically display after the promise resolves. – GPicazo Feb 09 '16 at 15:06

1 Answers1

1

Second alert will not show because there's nothing in $scope.orders when you alert it. That's the nature of asynchronous calls, only when you enter the success/error sections will you have something there (or not...).

Until the server returns your response and the success/error functions trigger, that variable is still unpopulated since $scope.orders=data hasn't run.

You should read the docs for some more info, and get some deeper understanding into how promises work.

Omri Aharon
  • 16,959
  • 5
  • 40
  • 58