1

I have created a service that deal with get and post request in angularJS but the problem is in my controller I couldn't catch the error call back however success callback is working good:

app.js

 AuthenticationService.Login(function (_data) {
    $rootScope.showPreloader = false;
    console.log(_data)//works fine when call is succes


    },function (error){
      console.log(error)//not executed when error is thrown  
    });

authentication.service.js

 function Login(callback) {
        $http({
            method: "GET",
            url: "/auth/getRoles",
            headers: {
                "Accept-Language": "en-US, en;q=0.8",
                "Content-Type": "application/json;charset=UTF-8"
            }
        }).then(function (_response) {
            return _response.data;

            var serverData = response.data;

            callback(serverData);//getting respone is controller when succes    

        }, _handleError);
    };

 function _handleError(_error) {

        console.log(_error)//console prints on error
        return _error//controller never recevies the return statement
         };

the problem is in handleError function which never returns the error to controller any help will be greatly appreacited

1

1 Answer 1

2

All you have to do is return the promise in your Login method

function Login(callback) {
    return $http(...success / error callback);
};

This way whichever method calls this is returned a promise that you can use ".then" on.

edit: It actually looks like you're really missing the point of promises here.

You define the method as above and then in some controller you can call on it as though it were a promise.

$scope.login = function() {

    LoginService.Login()
      .then(function(response){
        $scope.loginData = response
      }, function(err) {
      //Error handling...
      });

};

The benefit of this is that you can now do any kind of pre-processing necessary to manipulate the data in your LoginService and then you can just call is as a promise in any controller so long as you inject the login service.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.