角度回报承诺已有捕获

时间:2017-09-04 12:10:37

标签: angularjs promise

我有一个角度服务,提供登录功能以登录用户:

app.service('AuthSharedService', function($rootScope, $http, authService, UserSession) {
    this.login = function(email, password, rememberMe) {
        return $http.post('/login',
                {
                    'email': email,
                    'password': password,
                    'rememberMe': rememberMe
                })
            .then(function(response){
                console.log("success 1");
                authService.loginConfirmed(response.data);
            }).catch(function(response){
                console.log("catch 1");
            }).finally(function(response){
                console.log("finally 1");
            });
    };
    return this;
});

我还有一个绑定到HTML登录公式的控制器:

app.controller("loginController",
    function ($scope, $rootScope, $window, $http, $routeParams, AuthSharedService){
        var vm = this;
        vm.email;
        vm.password;
        vm.rememberMe;
        vm.login = function (){
            AuthSharedService.login(vm.email, vm.password, vm.rememberMe)
                .then(function(response){
                    console.log("success 2");
                }).catch(function(response){
                    console.log("catch 2");
                });
        }
    }
);

到目前为止,这是非常基本的 但是当我删除数据库用户表然后尝试登录时,我当然会在REST服务器上发生内部错误500。但是,有角度的控制台输出是:

catch 1
success 2

但为什么呢?我不能返回$http才能使用.then(function()).catch(function())两次?

感谢您的帮助:) 最好的问候

2 个答案:

答案 0 :(得分:2)

当你致电.catch时,它会返回一个承诺。如果您没有返回任何内容,它将返回自动解决的承诺。

如果您想在.catch之后将承诺保持在错误状态,您可以这样做:

promise
.catch(function(response) {
    handleResponse(response);
    return $q.reject(response);
});

你也可以这样做:

var promise = ...;
promise.catch(...);
return promise

请注意,如果catch回调是异步的,则此代码可能不会按您的意愿行事。

答案 1 :(得分:1)

tableView.selectRowAtIndexPath(index, animated: true, scrollPosition: UITableViewScrollPosition.middle) 返回一个默认成功的新承诺;这允许您创建捕获错误的链,然后继续一些默认的成功方案:

catch

这会提醒returnsPromise() .catch(() => 'default value') .then(value => alert(value)) 的值,如果失败则会提醒默认值returnsPromise

你想要的是返回原来的'default value'承诺,而不是被捕获的承诺:

$http

如果let p = $http.post(...); p.catch(...); return p; 失败,则会在发生错误时调用已附加的post() 以及您可能附加的任何其他错误处理程序。相反,只有catch成功,才会调用成功处理程序(并且p赢了)。

相关问题