如何在 angular http 请求的错误和成功回调之间共享变量

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

我想在 angular js 的 $http.get 请求的两种方法之间共享一个变量 我的代码看起来像这样

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

我的控制器代码如下所示

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

它始终输出 false,而如果我在两个函数中都发出警报响应,它就可以正常工作。

您混淆了 return 和承诺。 window.a 将在您的承诺 ($http.get) 解决时设置为异步,到那时您的具有初始值的 return 已经被 returned 和使用通过 alert().

您的操作方式不是处理异步调用的正确方法,根据当前的实现,它总是 return false 来自 checkSession 方法。您需要从异步处理的方法中 return promise 。该承诺将 return 来自其 resolvereject 的数据。

另外,我希望将此代码放在工厂中,而不是放在 $rootScope.

工厂

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

所以要在控制器中使用它,您首先需要在控制器工厂函数上注入 sessionFactory,然后在其上使用 checkSession 方法。在该方法的 .then 中,您将获得 returned 数据。

控制器

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