Prevent AngularJS $http return on timeout - javascript

I am doing custom $http service that looks something like this:
angular.factory('myHttp', function($http){
var obj = {};
obj.get = function(path) {
return $http.get(path,{timeout: 5000}).error(function (result) {
console.log("retrying");
return obj.get(path);
});
}
});
The system works fine. It does return the data when success, and retrying when connection fail. However, I am facing problem that it will return to controller when the connection is timeout. How can I prevent it from returning and continue retrying?

You need to use $q.reject. This will indicate that the error handler failed again and the result should populated to the parent error handler - NOT the success handler.
obj.get = function(path) {
return $http.get(path, {
timeout: 5000
}).then(null, function(result) {
console.log("retrying");
if (i < retry) {
i += 1;
return obj.get(path);
} else {
return $q.reject(result); // <-- use $q.reject
}
});
}
See plunker

See the reject.status to determine the timeout
$http.get('/path', { timeout: 5000 })
.then(function(){
// Your request served
},function(reject){
if(reject.status === 0) {
// $http timeout
} else {
// response error
}
});
Please see the following question for a good overview about handling timeout errors:
Angular $http : setting a promise on the 'timeout' config

Related

2 $http get function

Given 2 JSON url, how do I make sure the code has finished retrieving the data from a.json, then only start retrieving the data from b.json, then only run init function?
var aUrl = "a.json";
var bUrl = "b.json";
My attempt:
var app = angular.module('calendarApp', []);
app.controller('ctrl', function($scope, $http) {
$http.get(aUrl).success(function(data) { });
$http.get(bUrl).success(function(data) {
init()}
);
var init = function(){}
I faced the same issue in my initial days.
There are many ways of doing it exactly as suggested here.
You need to know below two things before exploring:
1. JavaScript is synchronous
Synchronous Example[Flow in sequence]:
console.log('1')
console.log('2')
console.log('3')
It logs 1 2 3.
Example of making service calls
1. $http.get(aUrl).success(function(data) { console.log('1.any time response returns') });
2. $http.get(bUrl).success(function(data) { console.log('2.mummy returns')};
So as single-threaded javascript will first make a call to your below code with $http.get(aUrl) which hits the url and processes to fetch the data from the background.
$http.get(aUrl).success(function(data) { console.log('1.any time response returns') });
But the key thing to notice here is $http.get(aUrl) requested above doesn't wait until the data is returned in success/error. It moves to the next request $http.get(bUrl) and we just can't predict which response comes earlier.
$http.get(bUrl).success(function(data) { console.log('2.mummy returns') }
Output might be either
1.any time response returns
2.mummy returns
or
2.mummy returns
1.any time response returns
So, to overcome this situation we follow asynchronous operations in various ways.
2. Asynchronous Calls
$http.get(aUrl)
.then(function(response){
console.log('inside the first then response');
console.log(response.data);
//executing the second request after we get the first request
//and returns the **outputResponse** which is captured in the next **then** block
return $http.get(bUrl);
})
.then(function(**outputResponse** ){
console.log('outputResponse generated from to the second bUrl');
//you can call init() here
});
Above code suffices your requirement.
Click for more info using $q in future
Click here to know why to use then instead of success.
Might not be the best or cleanest method but quickly making your code do what you want it to do I got:
var app = angular.module('calendarApp', []);
app.controller('ctrl', function($scope, $http) {
$http.get(aUrl).success(function(data) {
$http.get(bUrl).success(function(data) {
init()
}
});
);
var init = function(){}
You could create a service layer in which define the two methods. Then inject the service into your controller:
//Controller
YourService.getUrl(urlA).then(function(response) {
if(response != null && response.success == true){
// do something
}
YourService.getUrl(urlB).then(function(response) {
if(response != null && response.success == true){
// do something
init()
}
},
function errorCallback(response) {
console.log("Error YourService: getUrlB ---> ");
});
},
function errorCallback(response) {
console.log("Error YourService: getUrlA ---> ");
});
// Example of method in your service
this.getUrl = function(urlA) {
try{
var deferred = $q.defer();
$http({
method: 'GET',
url: getUrlA,
params: {},
responseType: "json",
cache: false
})
.success(function(data, status, headers, config) {
deferred.resolve(data);
})
.error(function(data, status, headers, config) {
deferred.reject(data);
});
return deferred.promise;
}catch(e){
/* */
console.log("Service: getUrl ---> " + e);
}
}
$http.get returns a promise, so you can do:
return $http.get(aUrl)
.then(function(result) {
return $http.get(bUrl);
})
.then(function(result) {
return init();
},
function (error) {
// do something with the error
});
I suggest to use AngularJS promises. Mainly it has the benefit of loading the data asynchronly at the same time without having to wait until the first request is finished. see: https://docs.angularjs.org/api/ng/service/$q
var promises = [];
var loadingJson = function(url){
var defer = $q.defer();
$http.get(url).then(function(results){
defer.resolve(results);
}, function(err){
defer.reject(err);
});
return defer.promise;
};
promise.push(loadingJson('example.com/1.json'));
promise.push(loadingJson('example.com/2.json'));
$q.all(promises).then(function(resultList){
// Your hanadling here, resultList contains the results of both API calls.
}, function(errList){
// Your error handling here.
});

AngularJS resolve promise before load route

I'm trying to make promise inside a factory and then validate in locationChangeStart. The problem is that the locationChangeStart doesn't wait for my promise. What can I do to make my promise wait to complete?
Here is my code,
app.run(['$rootScope','$location','KeyFactory',
function($root, $location,KeyFactory) {
$root.$on('$locationChangeStart', function(event, curr, prev) {
KeyFactory.check();
console.log(KeyFactory.GetKeyPass()); ///PRINT undefined
if(KeyFactory.GetKeyPass()== true){
console.log('authorised');
}else{
$location.path('/login');
}
});
}]);
app.factory('KeyFactory', ['$http','$log', function($http,$log) {
var key = {};
key.setKeyPass = function(set) {
key.Status = set;
}
key.GetKeyPass = function() {
return key.Status;
}
key.check = function(){
$http.post('http://localhost/api/CheckPass').success(function(data) {
console.log(data);
key.setKeyPass(true);
}).error(function (data, status){
$log.error("error you cant acess here!");
console.log(status);
});
}
return key;
}]);
Asynchronous code doesn't work in synchronous way as you are thinking. After making an ajax it doesn't respond in the next line. In angular after making an ajax it return an promise object which is responsible to tell that response/error is going to happen.
There are couple of things missing in your code.
You should return a promise from the check method of service.
Then put .then function on check method promise & expect response in its success/error callback.
Code
key.check = function(){
return $http.post('http://localhost/api/CheckPass').then(function(response) {
var data = response.data;
key.setKeyPass(true);
}, function (response){
key.setKeyPass(false);
});
Run
KeyFactory.check().then(function(){
if(KeyFactory.GetKeyPass()== true){
console.log('authorised');
}else{
$location.path('/login');
}
});

Global Error handler that only catches "unhandled" promises

I have a global error handler for my angular app which is written as an $http interceptor, but I'd like to take it a step further. What I'd like is for each $http call that fails (is rejected), any "chained" consumers of the promise should first try to resolve the error, and if it is STILL unresolved (not caught), THEN I'd like the global error handler to take over.
Use case is, my global error handler shows a growl "alert box" at the top of the screen. But I have a couple of modals that pop up, and I handle the errors explicitly there, showing an error message in the modal itself. So, essentially, this modal controller should mark the rejected promise as "handled". But since the interceptor always seems to be the first to run on an $http error, I can't figure out a way to do it.
Here is my interceptor code:
angular.module("globalErrors", ['angular-growl', 'ngAnimate'])
.factory("myHttpInterceptor", ['$q', '$log', '$location', '$rootScope', 'growl', 'growlMessages',
function ($q, $log, $location, $rootScope, growl, growlMessages) {
var numLoading = 0;
return {
request: function (config) {
if (config.showLoader !== false) {
numLoading++;
$rootScope.loading = true;
}
return config || $q.when(config)
},
response: function (response) {
if (response.config.showLoader !== false) {
numLoading--;
$rootScope.loading = numLoading > 0;
}
if(growlMessages.getAllMessages().length) { // clear messages on next success XHR
growlMessages.destroyAllMessages();
}
return response || $q.when(response);
},
responseError: function (rejection) {
//$log.debug("error with status " + rejection.status + " and data: " + rejection.data['message']);
numLoading--;
$rootScope.loading = numLoading > 0;
switch (rejection.status) {
case 401:
document.location = "/auth/login";
growl.error("You are not logged in!");
break;
case 403:
growl.error("You don't have the right to do this: " + rejection.data);
break;
case 0:
growl.error("No connection, internet is down?");
break;
default:
if(!rejection.handled) {
if (rejection.data && rejection.data['message']) {
var mes = rejection.data['message'];
if (rejection.data.errors) {
for (var k in rejection.data.errors) {
mes += "<br/>" + rejection.data.errors[k];
}
}
growl.error("" + mes);
} else {
growl.error("There was an unknown error processing your request");
}
}
break;
}
return $q.reject(rejection);
}
};
}]).config(function ($provide, $httpProvider) {
return $httpProvider.interceptors.push('myHttpInterceptor');
})
This is rough code of how I'd expect the modal promise call to look like:
$http.get('/some/url').then(function(c) {
$uibModalInstance.close(c);
}, function(resp) {
if(resp.data.errors) {
$scope.errors = resp.data.errors;
resp.handled = true;
return resp;
}
});
1. Solution (hacky way)
You can do that by creating a service doing that for you. Because promises are chain-able and you basically mark a property handled at the controller level, you should pass this promise to your service and it'll take care of the unhandled errors.
myService.check(
$http.get('url/to/the/endpoint')
.then( succCallback, errorCallback)
);
2. Solution (preferred way)
Or the better solution would be to create a wrapper for $http and do something like this:
myhttp.get('url/to/the/endpoint', successCallback, failedCallback);
function successCallback(){ ... }
function failedCallback(resp){
//optional solution, you can even say resp.handled = true
myhttp.setAsHandled(resp);
//do not forget to reject here, otherwise the chained promise will be recognised as a resolved promise.
$q.reject(resp);
}
Here the myhttp service call will apply the given success and failed callbacks and then it can chain his own faild callback and check if the handled property is true or false.
The myhttp service implementation (updated, added setAsHandled function which is just optional but it's a nicer solution since it keeps everything in one place (the attribute 'handled' easily changeable and in one place):
function myhttp($http){
var service = this;
service.setAsHandled = setAsHandled;
service.get = get;
function setAsHandled(resp){
resp.handled = true;
}
function get(url, successHandler, failedHandler){
$http.get(url)
.then(successHandler, failedHandler)
.then(null, function(resp){
if(resp.handled !== true){
//your awesome popup message triggers here.
}
})
}
}
3. Solution
Same as #2 but less code needed to achieve the same:
myhttp.get('url/to/the/endpoint', successCallback, failedCallback);
function successCallback(){ ... }
function failedCallback(resp){
//if you provide a failedCallback, and you still want to have your popup, then you need your reject.
$q.reject(resp);
}
Other example:
//since you didn't provide failed callback, it'll treat as a non-handled promise, and you'll have your popup.
myhttp.get('url/to/the/endpoint', successCallback);
function successCallback(){ ... }
The myhttp service implementation:
function myhttp($http){
var service = this;
service.get = get;
function get(url, successHandler, failedHandler){
$http.get(url)
.then(successHandler, failedHandler)
.then(null, function(){
//your awesome popup message triggers here.
})
}
}

success and error function in the controller for a service

I have the following code in a service and I am calling fetchData function from the controller.
Service
app.service("geturl", function($http) {
urllist = [];
geturl.fetchData = function() {
var data = [];
for (i = 0; i < urllist.length; i++) {
(function(index) {
return $http.get(geturl.urllist[index], {
timeout: 8000
})
.then(function(response) {
data[index] = response.data;
});
}(i);
return data;
});
};
});
I want to write the success and error function of $http.get in the controller since it is needed in the UI, how can I go about it?
..I want to write the success and error function of $http.get in the
controller..
Usually, the .then() function takes two function arguments. The first argument is the success handler and the second as an error handler.
$http.get(url,options).then(function (response){
//success handler function
},function(error){
//error handler function
})
Alternatively, you can specify the .success and .error functions separately.
$http.get(url,options).success(function (response){
//success handler function
}).error(function(error){
//error handler function
})
UPDATE:
From your code, it seems that you intend to return something from your service geturl and providing the callbacks there itself. This is not how it is supposed to be done. You should return a promise from your service .
...
app.service("geturl",function($http){
...
getData:function(){
return $http.get(url,options);
}
...
});
...
and handle the success/error callbacks in the module where you are consuming the service
geturl.getData().success(function(){
//handle success
}).error(function(){
//handle error
})
In case you need to make multiple http requests, never ever use the for loop . Remember, everything is asynchronous and you are not guaranteed to get the response from one of the previous request before you make a new one. In such scenarios, you should use $q service. See #pankajparkar's answer for more details
Seems like you want to return a data after all the ajax gets completed, You could achieve this by using $q.all()
Service
app.service("geturl", function($http, $q) {
this.urllist = [];
this.fetchData = function() {
var data = [], promises = [];
for (i = 0; i < urllist.length; i++) {
(function(index) {
var promise = $http.get(geturl.urllist[index], {
timeout: 8000
})
.then(function(response) {
data[index] = response.data;
});
promises.push(promise); //creating promise array
}(i);
};
return $q.all(promises).then(function(resp){
return data; //returning data after all promises completed
});
};
});

Promise chains don't work as expected

With the code below, my controller's publish() would always go to createCompleted() even if the server returned 500. I was under impression that catch() would be executed when 400 or 500 codes are returned from the server.
// in service
function create(item) {
return $http
.post(api, item)
.then(createCompleted)
.catch(createFailed);
function createCompleted(response) {
return response.data;
}
function createFailed(error) {
$log.error('XHR Failed for create: ' + error.data);
}
}
// in controller
function publish(item) {
item.published = true;
return itemService.create(item)
.then(createCompleted)
.catch(createFailed);
function createCompleted(response) {
alertService.add('success', 'success.');
$state.go('^');
}
function createFailed(error) {
alertService.add('error', 'failed');
}
}
While the controller's createFailed() doesn't hit, the service createFailed() always hits.
What is going on here?
Well that is because you are not propagating the error properly. you would need to throw an exception or reject explicitly from createFailed function.
function createFailed(error) {
$log.error('XHR Failed for create: ' + error.data);
throw error;
// or
return $q.reject(error); // inject $q
}
So in your case since you are not returning anything it is assumed to be resolved from the returned promise with the value "undefined".

Categories

Resources