In AngularJS, promises are typically handled using the $q
service. When dealing with errors in promises, you can use the .then()
method to specify a success callback and an error callback. Here's how you can handle errors in promises in AngularJS:
javascriptangular.module('myApp').controller('MyController', function($scope, $q, myService) {
$scope.getData = function() {
myService.getData()
.then(function(response) {
// Success callback
$scope.data = response.data;
})
.catch(function(error) {
// Error callback
console.error('Error fetching data:', error);
// You can also handle the error gracefully by displaying an error message to the user
$scope.errorMessage = 'Failed to fetch data. Please try again later.';
});
};
});
angular.module('myApp').service('myService', function($http, $q) {
this.getData = function() {
var deferred = $q.defer();
$http.get('/api/data')
.then(function(response) {
// Resolve the promise with the response data
deferred.resolve(response);
})
.catch(function(error) {
// Reject the promise with the error
deferred.reject(error);
});
return deferred.promise;
};
});
In this example:
myService
service fetches data from an API using $http.get()
.myService.getData()
, .then()
is used to handle the success case, and .catch()
is used to handle errors.By using .then()
and .catch()
on promises, you can effectively handle both successful responses and errors in your AngularJS application.