0

I am new to angularjs. I am using Angular 1.5 I want to load data from server and store it to scope and use it in view file.

My data is stored in the scope after load the view file. How can I store data to scope first and than load the view file so that I can use scope data in view file.

Here is my code

$scope.getProfile = function() {
        Account.getProfile()
            .then(function(response) {
                $scope.user = response.data;
                console.log($scope.user); //here data printed in console
            })
            .catch(function(response) {
                console.log(response.data.message, response.status);
            });
    };

if($auth.isAuthenticated()){
    $scope.getProfile();
    console.log($scope.user)//here data not print in console.
}
Igor
  • 60,821
  • 10
  • 100
  • 175
Md. Sahadat Hossain
  • 3,210
  • 4
  • 32
  • 55
  • Its because of Asyc calls! – Dhaval Marthak Apr 24 '17 at 05:18
  • @DhavalMarthak I know that. But I am new to `angularjs`. How can I solve it – Md. Sahadat Hossain Apr 24 '17 at 05:19
  • 2
    Possible duplicate of [How do I return the response from an asynchronous call?](http://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call) – Igor Apr 24 '17 at 05:19
  • Read the duplicate so you understand how asynchronous calls work in javascript and how to use them. In your case the call `getProfile` returns immediately but the request has gone to the server to do work. The next line will not yet have the result until that call completes. This call is known as a promise. – Igor Apr 24 '17 at 05:20
  • `But I am new to angularjs. How can I solve it` <= this is nothing specific to angularjs, its a core concept to using javascript and any type of external I/O communication from javascript (like calling a method on a remote server). – Igor Apr 24 '17 at 05:22

4 Answers4

1

Code in .then blocks execute asynchronously after the function returns.

Have the function return a promise for the value and extract that value in a .then block:

$scope.getProfile = function() {
    return Account.getProfile()
      .then(function(response) {
        $scope.user = response.data;
        console.log($scope.user); //here data printed in console
        return $scope.user;
    })
      .catch(function(response) {
        console.log(response.data.message, response.status);
        throw response;
    });
};

if($auth.isAuthenticated()){
    var promise = $scope.getProfile();
    promise.then(function(user) {
        console.log(user);
    });
};

By using a promise returned by the function, a .then block can be created that will execute after the data has returned from the server.


Explaination of Promise-Based Asynchronous Operations

console.log("Part1");
console.log("Part2");
var promise = $http.get(url);
promise.then(function successHandler(response){
    console.log("Part3");
});
console.log("Part4");

pic

The console log for "Part4" doesn't have to wait for the data to come back from the server. It executes immediately after the XHR starts. The console log for "Part3" is inside a success handler function that is held by the $q service and invoked after data has arrived from the server and the XHR completes.

For more information, see How to use $http promise response outside success handler.


Demo

console.log("Part 1");
console.log("Part 2");
var promise = new Promise(r=>r());
promise.then(function() {
    console.log("Part 3");
});
console.log("Part *4*");
Community
  • 1
  • 1
georgeawg
  • 48,608
  • 13
  • 72
  • 95
0

It's because of the Async behavior, you might need to use the callbacks. Give this a try

$scope.getProfile = function(callback) { //added callback function
  Account.getProfile()
    .then(function(response) {
      $scope.user = response.data;
      callback($scope.user); //callback execution
    })
    .catch(function(response) {
      console.log(response.data.message, response.status);
    });
};

And your caller should be like following:

if ($auth.isAuthenticated()) {
  $scope.getProfile(function(user){
    $scope.user = user;
  });
}

Hope this will help

Dhaval Marthak
  • 17,246
  • 6
  • 46
  • 68
  • when I console `$scope.user` outside of function than it returns undefined. In view file I can not print `user` data – Md. Sahadat Hossain Apr 24 '17 at 05:35
  • Some people consider putting a callback-based wrapper around a promise-based API an anti-pattern. See [Why are Callbacks from Promise `.then` Methods an Anti-Pattern](http://stackoverflow.com/questions/35660881/why-are-callbacks-from-promise-then-methods-an-anti-pattern). – georgeawg Apr 24 '17 at 10:21
0

If you want to execute some code every time an angular page loads, you could make use of ‘resolve’, as long as ‘UI-Router’ setup.

If you just want to execute some code without loading data, you are better off using ‘$viewContentLoading‘ or ‘$viewContentLoaded‘. Please note the following documentation.

You can refer here for more information

SAMUEL
  • 8,098
  • 3
  • 42
  • 42
-1

change your code as shown below:

    $scope.getProfile = function() {
        Account.getProfile()
                    .then(function(response) {
                        $scope.user = response.data;
                        console.log($scope.user); //here data printed in console
                        if($auth.isAuthenticated()){
                           console.log($scope.user)//here data not print in console.
                        }
                    })
                    .catch(function(response) {
                        console.log(response.data.message, response.status);
                    });
    };

$scope.getProfile();

Hope this helps. :-)

Pavan Kosanam
  • 79
  • 3
  • 13
  • This does not translate into what was posted in the OP. This could result in a `StackoverflowException` as it could recurs infinity. – Igor Apr 24 '17 at 05:25
  • Oops! Missed calling function to leave outside, now code edited. – Pavan Kosanam Apr 24 '17 at 05:33
  • No, the logic is still not right. I formatted the OPs code (no other changes, just indentation). Look again and see if you can spot the intent. – Igor Apr 24 '17 at 05:42