【问题标题】:call function A in function A after success call function B in angular js成功后在函数A中调用函数A 在角度js中调用函数B
【发布时间】:2015-11-17 01:04:29
【问题描述】:

我正在使用一些向服务器端发送 $http 异步请求的函数。如果响应为“notlogin”,我想在重新登录用户后调用相同的当前函数。我想我需要使用 Promise,但是如何使用?

 $scope.A = function(){
    $http({..,async: "isAsync",...})
    .success(function (response) {
        if (response.d == "notlogin") {
            if ($scope.B())//call back login to refresh session
                $scope.A();//repeat request if login return true
        }
    });
};

 $scope.B= function () {

        $scope.userlogin_error = "wait...";
        $http({...,async: "isAsync",...}).success(function (response) {

            if (response.d == "True") {
                $scope.userlogin_error = "login success";
                $scope.user_islogin = true;

                return true;
            }
});
}

【问题讨论】:

  • 什么是函数B
  • 是登录功能...

标签: jquery angularjs xmlhttprequest async-await angular-http


【解决方案1】:

尝试将 $scope.B() 设为 promise(这是异步的,我理解正确吗?);

$scope.B = function(){
    var defer = $q.defer();
    if(something) {
        defer.resolve(data);
    } else {
        defer.reject(error);
    }
    return defer.promise;
};

$scope.B().then(function(data){
    $scope.A();
});

【讨论】:

  • 如果scope.B 已经在使用$http 并且可以简单地返回该承诺,则这是一种反模式
  • 我是 Angular 的新手……你能把答案说清楚吗?我编辑了问题。
  • 我对此进行了测试,但 .then() 没有触发。我使用了 $scope.$apply(function() { defer.resolve(thing); });但没有工作
  • 感谢 @user3335966 我在您的解决方案中添加了 settimeout 并且效果很好。
【解决方案2】:

您可以通过返回 $http 调用来返回 $scope.B() 的成功回调

$scope.A = function(){
   $http({..,async: "isAsync",...}).success(function (response) {
    if (response.d == "notlogin") {
        $scope.B().success(function(data){
           if(data.d == "True"){
                $scope.userlogin_error = "login success";
                $scope.user_islogin = true;
                $scope.A();
           }
        });
    }
   });
};

 $scope.B= function () {
   return $http({...,async: "isAsync",...});
 };

【讨论】:

  • 在我的代码中,我返回布尔值而不是 $http 并且由于异步调用,调用函数 A 的条件不起作用。 bool 或 $http return 之间似乎没有区别。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2019-09-02
  • 1970-01-01
  • 1970-01-01
  • 2015-09-07
  • 1970-01-01
  • 2021-11-10
  • 2013-11-11
相关资源
最近更新 更多