简体   繁体   中英

AngularJS - Using then() with $http service

I noticed that I can use the $http provider in this way:

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.

            });

}]);

Notice the return statement in front of http and the use of then() on http instead of success().

Why does this work? Are there any downsides?

Try to chain the promise like that:

$http.post('URL', DATA)
    .success(function(data, status, headers, config)) {}) // on success callback
    .error(function(data, status, headers, config) {}); // on error callback
 $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
    }
 );

Angular $http service- success(), error(), then() methods

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