Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
133
rated 0 times [  140] [ 7]  / answers: 1 / hits: 23156  / 11 Years ago, fri, october 25, 2013, 12:00:00

I'm getting data from an async service inside my controller like this:



myApp.controller('myController', ['$scope', 'AsyncService',
function($scope, AsyncService) {
$scope.getData = function(query) {
return AsyncService.query(query).then(function(response) {
// Got success response, return promise
return response;
}, function(reason) {
// Got error, query again in one second
// ???
});
}
}]);


My questions:




  1. How to query the service again when I get error from service without returning the promise.

  2. Would it be better to do this in my service?



Thanks!


More From » angularjs

 Answers
10

You can retry the request in the service itself, not the controller.



So, AsyncService.query can be something like:



AsyncService.query = function() {
var counter = 0
var queryResults = $q.defer()

function doQuery() {
$http({method: 'GET', url: 'https://example.com'})
.success(function(body) {
queryResults.resolve(body)
})
.error(function() {
if (counter < 3) {
doQuery()
counter++
}
})
}

return queryResults.promise
}


And you can get rid of your error function in the controller:



myApp.controller('myController', ['$scope', 'AsyncService',
function($scope, AsyncService) {
$scope.getData = function(query) {
return AsyncService.query(query).then(function(response) {
// Got success response
return response;
});
}
}
]);

[#74725] Thursday, October 24, 2013, 11 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
cruzs

Total Points: 710
Total Questions: 113
Total Answers: 100

Location: Nepal
Member since Sat, Jul 18, 2020
4 Years ago
cruzs questions
Thu, Nov 26, 20, 00:00, 4 Years ago
Wed, Oct 28, 20, 00:00, 4 Years ago
Wed, Aug 19, 20, 00:00, 4 Years ago
Sun, Aug 2, 20, 00:00, 4 Years ago
;