简体   繁体   中英

Http service catch error angular js

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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