1

i want to share a variable between both methods of $http.get request of angular js my code looks like this

app.run(function($rootScope,$http) {
$rootScope.checkSession = function(){
  window.a = false;
    $http.get('/data/url')
    .success(function(response) {
      window.a = true;
    })
    .error(function(response){
      window.a = false;
    });
    return window.a;
};
});

and my controller code looks like this

app.controller('profileController', function($scope, $rootScope) {
   alert($rootScope.checkSession());
});

it is always output false while if i alert response in both functions it works fine.

1
  • window.a is returned before success or error comes.. this is wrong approach Commented Nov 4, 2015 at 18:58

2 Answers 2

3

You are confusing returns and promises. The window.a will be set async at the time your promise ($http.get) resolves, and by that time your return with the initial value has already been returned and used by alert().

Sign up to request clarification or add additional context in comments.

Comments

2

The way your are doing is not the correct way of dealing with asynchronous call, as per current implementation it will always return false from that checkSession method. You need to return promise from that method which dealing with asynchronously. That promise will return data from its resolve & reject.

Additional thing is, I would love to have this code inside a factory, rather than having in inside $rootScope.

Factory

app.factory('sessionFactory', function($http) {
  var sessionFactory = {}
  sessionFactory.checkSession = function(){
    return $http.get('/data/url')
    .then(function(response) {
      return true;
    },(function(response){
      return false;
    });
  };
  return sessionFactory;
});

So for using it in controller, you 1st need to inject sessionFactory on your controller factory function & then use checkSession method on it. Inside .then of that method you will have returned data.

Controller

app.controller('profileController', function($scope, sessionFactory) {
   sessionFactory.checkSession().then(function(data){
      alert(data);
   });
});

3 Comments

good example, just be aware that alert() probably won't work correctly with the promise.
@Maarten look at edit..Actually I was converting it to factory..to make that checkSession method rather than pollution $rootScope
@VivekMaru do look at updated which has better explaination... Glad to help you.. :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.