Angular HttpPromise: difference between `success`/`error` methods and `then`'s arguments

后端 未结 6 998
别那么骄傲
别那么骄傲 2020-11-22 16:59

According to AngularJS doc, calls to $http return the following:

Returns a promise object with the standard then

6条回答
  •  谎友^
    谎友^ (楼主)
    2020-11-22 17:24

    .then() is chainable and will wait for previous .then() to resolve.

    .success() and .error() can be chained, but they will all fire at once (so not much point to that)

    .success() and .error() are just nice for simple calls (easy makers):

    $http.post('/getUser').success(function(user){ 
       ... 
    })
    

    so you don't have to type this:

    $http.post('getUser').then(function(response){
      var user = response.data;
    })
    

    But generally i handler all errors with .catch():

    $http.get(...)
        .then(function(response){ 
          // successHandler
          // do some stuff
          return $http.get('/somethingelse') // get more data
        })
        .then(anotherSuccessHandler)
        .catch(errorHandler)
    

    If you need to support <= IE8 then write your .catch() and .finally() like this (reserved methods in IE):

        .then(successHandler)
        ['catch'](errorHandler)
    

    Working Examples:

    Here's something I wrote in more codey format to refresh my memory on how it all plays out with handling errors etc:

    http://jsfiddle.net/nalberg/v95tekz2/

提交回复
热议问题