简体   繁体   English

Angular $ http承诺无法解决

[英]Angular $http promise not resolving

I am currently working on building a login flow in AngularJS 1.3. 我目前正在AngularJS 1.3中构建登录流程。 My problem is that the promise return from an $http call is not resolving the code inside of its '.then'. 我的问题是,从$ http调用返回的promise不能解析其'.then'内部的代码。

I am working to handle error messages that come back from the server, specifically to handle any 401 errors which are returned when the user has input the wrong username or password. 我正在处理从服务器返回的错误消息,特别是处理用户输入错误的用户名或密码时返回的任何401错误。 However, when a 401 is returned, the .then never resolves itself and the code within them never runs. 但是,当返回401时,.then永远不会自行解析,并且其中的代码也永远不会运行。

The relevant code is as follows: 相关代码如下:

The controller for the login form as a login function on its scope, as follows: 作为其登录功能的登录表单的控制器,如下所示:

$scope.login = function() {
    $scope.authError = null;

    // Try to login
    var promise = session.login($scope.user);

    promise.then(function(loggedIn) {

        // THIS CODE NEVER RUNS

        if ( !loggedIn ) {
            $scope.authError = localizedMessages.get('login.error.invalidCredentials');
        }

    }, function(x) {
        $scope.authError = localizedMessages.get('login.error.serverError', { exception: x });
    });
};

I have a session factory that takes care of the login and other session based needs. 我有一个会话工厂,负责登录和其他基于会话的需求。 The code for login is: 登录代码为:

login: function(credentials) {
    var $http = $injector.get('$http');
    var url = ENV.apiEndpoint + "/sessions";

    var newSession = $http.post(url, credentials);

    return newSession.then(function(data) {
        session.set(data.token);

        //THIS CODE ONLY RUNS ON A SUCCESS RESPONSE

        if(session.isAuthenticated()) {
            closeLoginModal(true);
        }

        return session.isAuthenticated();
    });
}

I have placed comments in the code where the problem is. 我已经在问题所在的代码中添加了注释。 I am at a loss as to why this code isn't working. 我不知道为什么这段代码无法正常工作。 From my understanding of promises, then 'then' should resolve no matter what the response was, success of error. 从我对诺言的理解来看,无论回应是什么,“那么”都应该解决,即错误的成功。

I have an interceptor running, but I have tried disabling it with no luck to the end result. 我有一个拦截器正在运行,但是我尝试禁用它,但最终结果没有运气。

Am I missing something? 我想念什么吗?

If your login (server-side) returns an HTTP error code, like a 401, this should resolve to an error, eg, the second function passed to then . 如果您的登录名(服务器端)返回HTTP错误代码(例如401),则应解决错误,例如,传递给then的第二个函数。 If you don't pass one it should bomb out; 如果您不通过,它应该被炸开。 that's why your higher-level error function gets called. 这就是为什么您的高级错误函数会被调用的原因。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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