Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
828 views
in Technique[技术] by (71.8m points)

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

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 example that I can fetch the data using $http().then(), but I can't fetch my data using $http().success(). Can anyone explain why?

Code using $http.success() http://jsfiddle.net/xoonpLte/11/

var manuRep = angular.module('manuRep', ['ui.bootstrap']);
  manuRep.controller('MyAppController', function($scope, $http) {
    $http.get('https://dl.dropboxusercontent.com/u/59954187/jobs.json').
      success(function(response) {
        $scope.cats = response.data;    
      }).
      error(function(error){
        alert(JSON.stringify(error));
      return error;
      });
  });

Code using $http.then() http://jsfiddle.net/xoonpLte/12/

var manuRep = angular.module('manuRep', ['ui.bootstrap']);
  manuRep.controller('MyAppController', function($scope, $http) {
    $http.get('https://dl.dropboxusercontent.com/u/59954187/jobs.json').
      then(function(response) {
        $scope.cats = response.data;    
      });
  });
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

.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
    })


}]);

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...