简体   繁体   中英

How to share a variable between error and success callback of angular http request

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.

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().

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);
   });
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM