AngularJS — использование then() с сервисом $http

Я заметил, что могу использовать провайдера $http следующим образом:

Auth.login(userdetails).then(function(response){
//...
}

app.service('Auth', ['$http', function ($http) {

    AuthService.login = function (credentials) {

        return $http.
            post('getauth.php', credentials).
            then(function (res) {

                //create the session, etc.

            });

}]);

Обратите внимание на оператор return перед http и использование then() в http вместо success().

Почему это работает? Есть ли недостатки?


person reggie    schedule 04.12.2014    source источник
comment
возможный дубликат Angular HTTPPromise   -  person Anubhav    schedule 04.12.2014
comment
Я только что ответил на этот stackoverflow.com/questions/27287731/   -  person Chandermani    schedule 04.12.2014


Ответы (2)


Попробуйте связать обещание следующим образом:

$http.post('URL', DATA)
    .success(function(data, status, headers, config)) {}) // on success callback
    .error(function(data, status, headers, config) {}); // on error callback
person Muhammad Reda    schedule 04.12.2014
comment
Может быть, я был не ясен. Мой код не сломан, он работает. - person reggie; 04.12.2014

 $http({
        url: 'put url here',
        method: "put action here just like GET/POST",
        data: { 'name': 'Anil Singh' }
    })
    .then(function (resp) {
        //TODO: put success logic here
    },
    function (resp) {
        //TODO:  put failed logic here
    }
 );

https://stackoverflow.com/questions/27287731/angular-http-service-success-error-then-methods/27288310#27288310

person Community    schedule 04.12.2014