-->

How to define an error callback in AngularJS?

2019-07-12 20:32发布

问题:

In my 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
}

and in my 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);
       }
    );
}

When my POST delivers a 200 response code, everything works as expected do something after success is executed.

But when my POST results e.g. in a 401 I can see that Messages.create is called (so in this case it enters the error path), but unfortunately my Controller calls the successCallback and not the errorCallback.

I had to migrate this because I was using the deprecated and since Angular 1.6 removed .success and .error promise attributes. It was working back then, but after migration this doesn't work anymore.

What am I doing wrong here?

回答1:

You may reject the promise in your error callback.

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);
       }
    );
}

From 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.