Angular $http difference between .success() and .then()

后端 未结 4 1045
半阙折子戏
半阙折子戏 2021-01-24 23:47

Sometimes I have trouble to fetch my data using $http service. And I did not 100% understand the main difference between .success() and .then()

The following is an examp

4条回答
  •  夕颜
    夕颜 (楼主)
    2021-01-25 00:11

    .then is a promises

    .success and .error is a callback.

    Why callbacks or Promises?

    1 . Promises can handle global errors.
    2 . Promises can be chained (you don't have this encapsulation like callbacks)

    P = promise,
    R = response,
    E = error.

    1:

    P1(R1)
    .P2(R2)
    .P3(R3, E3)  
    

    Error 3 will be called if there is an error in promise 1, 2 or 3.
    That is not possible with callbacks.

    2:
    If you have 3 promises:

    P1(R1, E1)
    .P2(R2, E2)
    .P3(R3,E3)
    

    If you have 3 callbacks

    P1().success(P2().success(P3().success().error()).error()).error()
    

    EDIT

    .service('Auth', function(){
      this.isLoggedIn = function(){
         return $http.get('url/isLoggedIn');
      };
    })
    
    .service('getData', function(){
      this.name = function(){
        return $http.get('url/data/name');
      }
    })
    
    .controller('MyCTRL', ['Auth', 'getData', function(auth, getData){
    
       Auth.isLoggedIn().then(function(resp){
         return getData.name(); //By sending a value back inthe response, next response is called
       })
       .then(function(res){
            //Here we are
        }, function(err){
            //Global error.
            //This will be called in P1 or P2
        })
    
    
    }]);
    

提交回复
热议问题