如何在AngularJS中定义错误回调?

How to define an error callback in AngularJS?

在我的 Controller:

function login(credentials) {
  AuthService
    .login(credentials)
    .then(successCallback, errorCallback);
    //same issue with .then(successCallback).catch(errorCallback);
}

function successCallback() {
  // do something after success
}

function errorCallback(data) {
  // do something after error
}

在我的 AuthService:

authService.login = function (credentials) {
  return $http
    .post(ENV.apiEndpoint + 'api/v1/login_check', credentials)
    .then(
       function (result) {
        Session.create(result.data.token, result.data.data);
       },
       function (data) {
        Messages.create('Login failed: ' + data.statusText);
       }
    );
}

当我的 POST 提供 200 响应代码时,一切都按预期运行 do something after success 已执行。

但是当我的 POST 结果例如在 401 中我可以看到 Messages.create 被调用(所以在这种情况下它进入 error 路径),但不幸的是我的控制器调用 successCallback 而不是 errorCallback

我不得不迁移它,因为我使用的是已弃用的,并且自从 Angular 1.6 删除了 .success.error promise 属性。当时还可以,但迁移后就不行了。

我做错了什么?

您可以拒绝错误回调中的承诺。

authService.login = function (credentials) {
  return $http
    .post(ENV.apiEndpoint + 'api/v1/login_check', credentials)
    .then(
       function (result) {
         Session.create(result.data.token, result.data.data);
       },
       function (data) {
         Messages.create('Login failed: ' + data.statusText);
         return $q.reject(data);
       }
    );
}

来自Angular $q doc

reject(reason);

Creates a promise that is resolved as rejected with the specified reason. This api should be used to forward rejection in a chain of promises. If you are dealing with the last promise in a promise chain, you don't need to worry about it.

When comparing deferreds/promises to the familiar behavior of try/catch/throw, think of reject as the throw keyword in JavaScript. This also means that if you "catch" an error via a promise error callback and you want to forward the error to the promise derived from the current promise, you have to "rethrow" the error by returning a rejection constructed via reject.