angularjs - Angular $http difference between .success() and .then() -
sometimes have trouble fetch data using $http service. , did not 100% understand main difference between .success() , .then()
the following example can fetch data using $http().then(), can't fetch data using $http().success(). can 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; }); });
.then
promises
.success
, .error
callback.
why callbacks or promises?
1 . promises can handle global errors.
2 . promises can chained (you don't have encapsulation callbacks)
p = promise,
r = response,
e = error.
1:
p1(r1) .p2(r2) .p3(r3, e3)
error 3 called if there error in promise 1, 2 or 3.
not possible callbacks.
2:
if have 3 promises:
p1(r1, e1) .p2(r2, e2) .p3(r3,e3)
if 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 value inthe response, next response called }) .then(function(res){ //here }, function(err){ //global error. //this called in p1 or p2 }) }]);
Comments
Post a Comment