在AngularJS中有一个在$http之后运行的finally

In AngularJS is there such a thing as a finally that runs after $http?

本文关键字:运行 finally 之后 AngularJS 有一个 http      更新时间:2023-09-26

我的代码如下:

  $scope.login = function (userName, password, rememberMe) {
        authentication.authenticating = true;
        var config = {
            method: 'POST',
            url: '/api/Account/Login',
            data: { 'userName': userName, 'password': password, 'rememberMe': rememberMe }
        };
        $http(config)
            .success(function (data) {
                authentication.authenticating = false;
                authentication.isAuthenticated = true;
                $scope.template = $scope.templates[1];
                $scope.userName = userName;
            })
            .error(function (data) {
                $scope.loginError = "Invalid username/password combination";
                authentication.authenticating = false;
            });
    };

有没有办法移动authentication.authentication=false;转换成某个总是在错误或成功后执行的代码块?

是的,由于$http返回promise,因此可以调用.finally(callback)方法,如$q文档中所述https://docs.angularjs.org/api/ng/service/$q

所以你可以像这个一样在你的情况下使用它

$scope.login = function (userName, password, rememberMe) {
    authentication.authenticating = true;
    var config = {...};
    $http(config)
        .success(function (data) {
            authentication.isAuthenticated = true;
            $scope.template = $scope.templates[1];
            $scope.userName = userName;
        })
        .error(function (data) {
            $scope.loginError = "Invalid username/password combination";
        })
        .finally(function() {
            authentication.authenticating = false;
        });
};

尝试promise($q)

使用$q.delated获取对象,然后可以在成功或错误中使用resolve或reject http方法

对不起,我的回答很简短。

您可以将代码移动到另一个方法中,就像这样,但您仍然需要从成功或失败函数中手动调用它:

  var setAuthenticating = function(){
                authentication.authenticating = false;
  }
  $scope.login = function (userName, password, rememberMe) {
        authentication.authenticating = true;
        var config = {
            method: 'POST',
            url: '/api/Account/Login',
            data: { 'userName': userName, 'password': password, 'rememberMe': rememberMe }
        };
        $http(config)
            .success(function (data) {
                setAuthenticating();
                authentication.isAuthenticated = true;
                $scope.template = $scope.templates[1];
                $scope.userName = userName;
            })
            .error(function (data) {
                $scope.loginError = "Invalid username/password combination";
                setAuthenticating();
            });
    };