Vishnu
Vishnu

Reputation: 12323

Un Ordered execution of the instructions

When I am calling Details function it is giving empty details because Details function is executing before getting the data from the json file. How to resolve the problem?

app.controller('loginCtrl',function($scope,login){
 $scope.user=login.Details();
}

app.factory('login',function($cookieStore,$http){
 var users=[];
 $http.get("js/user.json").success(function(data){
    angular.copy(data,users);
 });
return{
 Details:function()
    {
        alert(users);
        return users;
    }
}

Upvotes: 0

Views: 50

Answers (2)

Dan Cowell
Dan Cowell

Reputation: 385

You need to update $scope.user in the success callback of your $http.get. The best way to do that is to define the success function in your controller and pass it into your service. So your service becomes:

app.factory('login', function($cookieStore,$http){
    var userCache;

    return {
        doLogin: function(user, password, successCallback) {
            if(!userCache) {
                $http.get("js/user.json").success(function(data) {
                    userCache = data;
                    successCallback(data);
                });
            }
        }
    }
}

and your controller gets this added somewhere in a click handler or something:

login.doLogin('sampleUsername', 'samplePassword', function(data) {
    $scope.user = data;
});

That should do most of what you need, you might need to adjust depending on how you're validating logins and what that sample JSON file contains. Good luck.

Upvotes: 1

Milad
Milad

Reputation: 28610

Of cousre it wil give You empty user , because you've defined your var user=[]; and then and Ajax call , and then you are returning that user , So because you're not doing this asynchronously , all of them will fire synchronous and Javascript will be pleased to return an emtpy user :!!!

There are some ways to solve this , using promise is one of them

   app.factory('login',function(){
     return{
       Details:function(){
         promise = $http.get("js/user.json");
         promise.then(function(data){
           return data;
      });
    }

   }
         });

OR you can Simply do this :

 app.factory('login',function(){
     return{
         Details:function(){
             $http.get("js/user.json")
                 .success(function(data){
                     return data;
                 })
                       }
                }

          });

Upvotes: 0

Related Questions