Setting timeout in $http Service AngularJS 1.5.5 - angularjs

I have my controller calling the api and by the time the api returns results I have the 500 Internal server in the chrome console popping up. I am using angular 1.5.5, could you please help with some timeout code.
Tried using .timeout(3000,new Error(timeout exceeded)) before .then but it does not compile
angular.module('myApp').factory('submitService',function($http)){
var service={};
service.getJwtToken=function(user)
{
return $http({
method: "POST",
url:"http://localhost:5000/jwtTest",
data: user
}).then(function(resp){
return resp;
});
}
return service;
});

You can try with setInterval
setInterval(function () {
//Call your Service here
}, 5000);
This server error occurs because there may be missing param or something like this
//if 'function2' is dependent on any condition of 'function1' call like this
var f1 = yourService.function1(param1);
f1.then(function (data1) {
if(data1){
var f2 = yourService.function2(param2);
f2.then(function (data2) {
//Do code
});
}
});
//if 'function2' and 'function1' are independent call like this
var f1 = yourService.function1(param1);
f1.then(function (data1) {
//Do code
});
var f2 = yourService.function2(param2);
f2.then(function (data2) {
//Do code
});

To set a timeout of for the $http service, use the timeout property of the config object:
app.factory('submitService', function ($http) {
var service = {};
service.getJwtToken = function (user) {
var config = { timeout: 3000 };
return $http.post("http://localhost:5000/jwtTest", user, config);
};
return service;
});
From the Docs:
config object
Object describing the request to be made and how it should be processed. The object has following properties:
timeout – {number|Promise} – timeout in milliseconds, or promise that should abort the request when resolved.
A numerical timeout or a promise returned from $timeout, will set the xhrStatus in the response to "timeout", and any other resolved promise will set it to "abort", following standard XMLHttpRequest behavior.
For more information, see
AngularJS $http Service API Reference - Arguments

Related

$http.get doesn't work with REST model using then() function

As you guys know, Angular recently deprecated the http.get.success,error functions. So this kind of calls are not recommended in your controller anymore:
$http.get("/myurl").success(function(data){
myctrl.myobj = data;
}));
Rather, this kind of calls are to be used:
$http.get("/myurl").then(
function(data) {
myctrl.myobj = data;
},
function(error) {
...
}
Problem is, simple Spring REST models aren't working with this new code. I recently downloaded a sample code with the above old success function and a REST model like this:
#RequestMapping("/resource")
public Map<String,Object> home() {
Map<String,Object> model = new HashMap<String,Object>();
model.put("id", UUID.randomUUID().toString());
model.put("content", "Hello World");
return model;
}
This should return a map like {id:<someid>, content:"Hello World"} for the $http.get() call, but it receives nothing - the view is blank.
How can I resolve this issue?
The first (of four) argument passed to success() is the data (i.e. body) of the response.
But the first (and unique) argument passed to then() is not the data. It's the full HTTP response, containing the data, the headers, the status, the config.
So what you actually need is
$http.get("/myurl").then(
function(response) {
myctrl.myobj = response.data;
},
function(error) {
...
});
The expectation of the result is different. Its the response and not the data object directly.
documentation says :
// Simple GET request example:
$http({
method: 'GET',
url: '/someUrl'
}).then(function successCallback(response) {
// this callback will be called asynchronously
// when the response is available
}, function errorCallback(response) {
// called asynchronously if an error occurs
// or server returns response with an error status.
});
Properties of the response are
data – {string|Object} – The response body transformed with the transform functions.
status – {number} – HTTP status code of the response.
headers – {function([headerName])} – Header getter function.
config – {Object} – The configuration object that was used to generate the request.
statusText – {string} – HTTP status text of the response.
As the data object is required,
Please convert the code as
$http.get("/resource").then(
function(response) {
myctrl.myobj = response.data;
});
then must be return a new promise so you should handle it with defers.
var myApp = angular.module('myApp', []);
myApp.factory('modelFromFactory', function($q) {
return {
getModel: function(data) {
var deferred = $q.defer();
var items = [];
items.push({"id":"f77e3886-976b-4f38-b84d-ae4d322759d4","content":"Hello World"});
deferred.resolve(items);
return deferred.promise;
}
};
});
function MyCtrl($scope, modelFromFactory) {
modelFromFactory.getModel()
.then(function(data){
$scope.model = data;
})
}
Here is working fiddle -> https://jsfiddle.net/o16kg9p4/7/

I set the service data,but after $http done, I cannot get the service data

My service define like this:
module.factory('portfolio',function(){
var data;
var selectedPort;
return{
getData: function(){
return data;
},
setData:function(portfolios){
data = portfolios;
},
getSelectedPort:function(){
return selectedPort;
},
setSelectedPort:function(portfolioDetail){
selectedPort = portfolioDetail;
}
}
});
And in my controller the code as follows:
module.controller('portfoliosController', function($scope,$http, alertService,stockService, userDataService, portfolio){
var req = {
method: 'get',
url: 'www.facebook.com',
headers: {
'Authorization': userDataService.getToken()
}
};
$http(req).then(function(reponse){
$scope.portfoliosPriceList = reponse['data'];
portfolio.setData($scope.portfoliosPriceList);
console.log(portfolio.getData())//At here,I can get the portfolio's data
}, function(){
alertService.setMessge("System maintenance , please try again later");
alertService.alert();
});
console.log(portfolio.getData())//At here, I cannot get the portfolio's data
});
the error is
Error: undefined is not an object (evaluating 'message.substr')
Anybody can help me to solve this problem?Actually, I really do not understand, why I cannot get the data outside the $http
The request that you do with the $http service is done asynchronously, so the callback that you pass to the .send is not immediately invoked.
The code that follows (the console.log) is executed just after the $http(req) call is made but before the callback is called when the request is responded.
Maybe you will understand better with an simpler example:
function portfoliosController() {
var data = 'Initial Data. ',
content = document.getElementById('content');
// setTimeout would be your $http.send(req)
// calledLater would be your .then(function() { ... })
setTimeout(function calledLater() {
data = 'Data coming from the server takes some time to arrive...';
content.innerHTML = content.innerHTML + data;
}, 1000);
content.innerHTML = content.innerHTML + data;
}
portfoliosController();
<div id="content">
This is because javascript is asynchronous, so the code:
portfolio.getData()
Is maybe executing before the data is returned from the service.
In this case, you should only use the data of the portfolio just after the request is complete (inside the .then() function of $http) or put a promise.
Here is the documentation for angular promises:
https://docs.angularjs.org/api/ng/service/$q

Angularjs how to cancel resource promise when switching routes

I'm just getting my feet wet with Angularjs. I have an issue which I think has something to do with promises.
Let's say I load route 'A' which makes several ajax requests through it's controller:
allSites = AllSites.query({ id:categoryID });
allSites.$promise.then(function(allSites){
//add stuff to the scope and does other things
//(including making another ajax request)
});
Then I have route 'B' which makes it's own API request through it's controller:
$scope.categories = Category.query();
Here's the factory service currently used by route 'A':
.factory('AllSites',function($resource){
return $resource('api/categorySites/:id');
});
When I first view route 'A' but then switch to 'B' before 'A' is finished loading, route 'B' sits and waits for everything initially requested in 'A' to finish (actually, the query() request is made, but it won't resolve until the one from 'A' does, at that point, the stuff inside .then() continues to happen, even though I don't need it as I'm now on another route.
As you can see in my devtools timeline, the green line indicates when I switched to route 'B'. The request for route 'B' didn't resolve until the two requests above did (a request that is usually very fast). (at which point I'm able to use the view as a user). Then, after that, more promises resolve from route 'A'.
I've searched everywhere for an answer and can only find people that want to "defer" the route loading until promises are resolved. But in my case I almost want the opposite. I want to kill those requests when I switch.
Here's someone else with the same, unanswered question: Reject Angularjs resource promises
Any help is appreciated.
First of all, I decided I needed to use $http since I couldn't find any solution that used $resource, nor could I get it to work on my own.
So here's what my factory turned into, based on #Sid's answer here, using the guide at http://www.bennadel.com/blog/2616-aborting-ajax-requests-using-http-and-angularjs.htm
.factory('AllSites',function($http,$q){
function getSites(categoryID) {
// The timeout property of the http request takes a deferred value
// that will abort the underying AJAX request if / when the deferred
// value is resolved.
var deferredAbort = $q.defer();
// Initiate the AJAX request.
var request = $http({
method: 'get',
url: 'api/categorySites/'+categoryID,
timeout: deferredAbort.promise
});
// Rather than returning the http-promise object, we want to pipe it
// through another promise so that we can "unwrap" the response
// without letting the http-transport mechansim leak out of the
// service layer.
var promise = request.then(
function( response ) {
return( response.data );
},
function() {
return( $q.reject( 'Something went wrong' ) );
}
);
// Now that we have the promise that we're going to return to the
// calling context, let's augment it with the abort method. Since
// the $http service uses a deferred value for the timeout, then
// all we have to do here is resolve the value and AngularJS will
// abort the underlying AJAX request.
promise.abort = function() {
deferredAbort.resolve();
};
// Since we're creating functions and passing them out of scope,
// we're creating object references that may be hard to garbage
// collect. As such, we can perform some clean-up once we know
// that the requests has finished.
promise.finally(
function() {
promise.abort = angular.noop;
deferredAbort = request = promise = null;
}
);
return( promise );
}
// Return the public API.
return({
getSites: getSites
});
});
Then, in my controller (route 'A' from my problem):
var allSitesPromise = AllSites.getSites(categoryID);
$scope.$on('$destroy',function(){
allSitesPromise.abort();
});
allSitesPromise.then(function(allSites){
// do stuff here with the result
}
I wish the factory wasn't so messy, but I'll take what I can get. However, now there's a separate, related issue Here where, though the promise was cancelled, the next actions are still delayed. If you have an answer for that, you can post it there.
There is a similar question with the answer "How to cancel $resource requests".
While it does not address the question exactly it gives all ingredients to cancel resource request when route is switched:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>Cancel resource</title>
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.3.9/angular.js"></script>
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.3.9/angular-resource.js"></script>
<script>
angular.module("app", ["ngResource"]).
factory(
"services",
["$resource", function($resource)
{
function resolveAction(resolve)
{
if (this.params)
{
this.timeout = this.params.timeout;
this.params.timeout = null;
}
this.then = null;
resolve(this);
}
return $resource(
"http://md5.jsontest.com/",
{},
{
MD5:
{
method: "GET",
params: { text: null },
then: resolveAction
},
});
}]).
controller(
"Test",
["services", "$q", "$timeout", function(services, $q, $timeout)
{
this.value = "Sample text";
this.requestTimeout = 100;
this.call = function()
{
var self = this;
self.result = services.MD5(
{
text: self.value,
timeout: $q(function(resolve)
{
$timeout(resolve, self.requestTimeout);
})
});
}
}]);
</script>
</head>
<body ng-app="app" ng-controller="Test as test">
<label>Text: <input type="text" ng-model="test.value" /></label><br/>
<label>Timeout: <input type="text" ng-model="test.requestTimeout" /></label><br/>
<input type="button" value="call" ng-click="test.call()"/>
<div ng-bind="test.result.md5"></div>
</body>
</html>
How it works
$resource merges action definition, request params and data to build a config parameter for an $http request.
a config parameter passed into an $http request is treated as a promise like object, so it may contain then function to initialize config.
action's then function may pass timeout promise from params into the config.
Please look at "Cancel Angularjs resource request" for details.
Take a look at this post
You could do what he is doing and resolve the promise to abort the request on a route change (or state change if using ui router).
It may not be the easiest thing to make happen but seems like it can work.
I cancel the promise with $q.reject(). I think that this way is more simple:
In SitesServices.js:
;(() => {
app.services('SitesServices', sitesServices)
sitesServices.$inject = ['$http', '$q']
function sitesServices($http, $q) {
var sitesPromise = $q.defer()
this.getSites = () => {
var url = 'api/sites'
sitesPromise.reject()
sitesPromise = $q.defer()
$http.get(url)
.success(sitesPromise.resolve)
.error(sitesPromise.reject)
return sitesPromise.promise
}
}
})()
In SitesController.js:
;(() => {
app.controller('SitesController', sitesControler)
sitesControler.$inject = ['$scope', 'SitesServices']
function sitesControler($scope, SitesServices) {
$scope.sites = []
$scope.getSites = () => {
SitesServices.getSites().then(sites => {
$scope.sites = sites
})
}
}
})()
Checking the docs for $resource I found a link to this little beauty.
https://docs.angularjs.org/api/ng/service/$http#usage
timeout – {number|Promise} – timeout in milliseconds, or promise that
should abort the request when resolved.
I've used it with some success. It go a little something like this.
export default function MyService($q, $http) {
"ngInject";
var service = {
getStuff: getStuff,
};
let _cancelGetStuff = angular.noop;
return service;
function getStuff(args) {
_cancelGetStuff(); // cancel any previous request that might be ongoing.
let canceller = $q( resolve => { _cancelGetStuff = resolve; });
return $http({
method: "GET",
url: <MYURL>
params: args,
timeout: canceller
}).then(successCB, errorCB);
function successCB (response) {
return response.data;
}
function errorCB (error) {
return $q.reject(error.data);
}
}
}
Keep in mind
This assumes you only want the results from the last request
The canceled requests still call successCB but the response is undefined.
It may also call errorCB, the error.status will be -1 just like if the request timed out.

Cancelling a request with a $http interceptor?

I'm trying to figure out if it is possible to use a $http interceptor to cancel a request before it even happens.
There is a button that triggers a request but if the user double-clicks it I do not want the same request to get triggered twice.
Now, I realize that there's several ways to solve this, and we do already have a working solution where we wrap $http in a service that keeps track of requests that are currently pending and simply ignores new requests with the same method, url and data.
Basically this is the behaviour I am trying to do with an interceptor:
factory('httpService', ['$http', function($http) {
var pendingCalls = {};
var createKey = function(url, data, method) {
return method + url + JSON.stringify(data);
};
var send = function(url, data, method) {
var key = createKey(url, data, method);
if (pendingCalls[key]) {
return pendingCalls[key];
}
var promise = $http({
method: method,
url: url,
data: data
});
pendingCalls[key] = promise;
promise.finally(function() {
delete pendingCalls[key];
});
return promise;
};
return {
post: function(url, data) {
return send(url, data, 'POST');
}
}
}])
When I look at the API for $http interceptors it does not seem to be a way to achieve this. I have access to the config object but that's about it.
Am I attempting to step outside the boundaries of what interceptors can be used for here or is there a way to do it?
according to $http documentation, you can return your own config from request interceptor.
try something like this:
config(function($httpProvider) {
var cache = {};
$httpProvider.interceptors.push(function() {
return {
response : function(config) {
var key = createKey(config);
var cached = cache[key];
return cached ? cached : cached[key];
}
}
});
}
Very old question, but I'll give a shot to handle this situation.
If I understood correctly, you are trying to:
1 - Start a request and register something to refer back to it;
2 - If another request takes place, to the same endpoint, you want to retrieve that first reference and drop the request in it.
This might be handled by a request timeout in the $http config object. On the interceptor, you can verify it there's one registered on the current request, if not, you can setup one, keep a reference to it and handle if afterwards:
function DropoutInterceptor($injector) {
var $q = $q || $injector.get('$q');
var dropouts = {};
return {
'request': function(config) {
// I'm using the request's URL here to make
// this reference, but this can be bad for
// some situations.
if (dropouts.hasOwnProperty(config.url)) {
// Drop the request
dropouts[config.url].resolve();
}
dropouts[config.url] = $q.defer();
// If the request already have one timeout
// defined, keep it, othwerwise, set up ours.
config.timeout = config.timeout || dropouts[config.url];
return config;
},
'requestError': function(reason) {
delete dropouts[reason.config.url];
return $q.reject(reason);
},
'response': function(response) {
delete dropouts[response.config.url];
return response;
},
'responseError': function(reason) {
delete dropouts[reason.config.url];
return $q.reject(reason);
}
};
}

How to set a global http timeout in AngularJs

I know I can set a timeout each and every time:
$http.get('path/to/service', {timeout: 5000});
... but I want to set a global timeout to keep my code DRY.
This is possible with bleeding-edge angular.js (tested with git master 4ae46814ff).
You can use request http interceptor. Like this.
angular.module('yourapp')
.factory('timeoutHttpIntercept', function ($rootScope, $q) {
return {
'request': function(config) {
config.timeout = 10000;
return config;
}
};
});
And then in .config inject $httpProvider and do this:
$httpProvider.interceptors.push('timeoutHttpIntercept');
UPDATED: $http will not respect default setting for timeout set it in httpProvider (see the comments). Possible workaround: https://gist.github.com/adnan-i/5014277
Original answer:
angular.module('MyApp', [])
.config(['$httpProvider', function($httpProvider) {
$httpProvider.defaults.timeout = 5000;
}]);
Thanks for the post and update!!
In researching this issue specifically for $resource, I thought I'd elaborate on what I've found:
This issue was logged in the tracker and in angular 1.1.5, there is support for passing the timeout property through to the $http request:
https://github.com/angular/angular.js/issues/2190
http://code.angularjs.org/1.1.5/docs/api/ngResource.$resource
For those of us on earlier versions, specifically I am using angular 1.0.6, it is possible to edit the source file for angular-resource.js on line 396 you will find the call to $http where you can add the timeout property yourself for all resource requests.
Since it wasn't mentioned and I had to test Stewie's solution, when a timeout does occur, the way to tell between an error and an abort/timeout is checking the 'status' argument. It will return 0 for timeouts instead of say 404:
$http.get("/home", { timeout: 100 })
.error(function(data, status, headers, config){
console.log(status)
}
Since there are only a few cases where I need to use a timeout as opposed to setting it globally, I am wrapping the requests in a $timeout function, like so:
//errorHandler gets called wether it's a timeout or resource call fails
var t = $timeout(errorHandler, 5000);
myResource.$get( successHandler, errorHandler )
function successHandler(data){
$timeout.cancel(t);
//do something with data...
}
function errorHandler(data){
//custom error handle code
}
I've the same requirement and I m using AngularJS 1.0.7. I've come up with the below code as none of the above solutions seems feasible for me (feasible in the sense I want timeout to be global at one place). Basically, I m masking the original $http methods and adding timeout for each $http request and overriding other shortcut methods, like get, post, ... so that they'll use the new masked $http.
JSFiddle for below code:
/**
* #name ngx$httpTimeoutModule
* #description Decorates AngularJS $http service to set timeout for each
* Ajax request.
*
* Implementation notes: replace this with correct approach, once migrated to Angular 1.1.5+
*
* #author Manikanta G
*/
;(function () {
'use strict';
var ngx$httpTimeoutModule = angular.module('ngx$httpTimeoutModule', []);
ngx$httpTimeoutModule.provider('ngx$httpTimeout', function () {
var self = this;
this.config = {
timeout: 1000 // default - 1 sec, in millis
};
this.$get = function () {
return {
config: self.config
};
};
});
/**
* AngularJS $http service decorator to add timeout
*/
ngx$httpTimeoutModule.config(['$provide', function($provide) {
// configure $http provider to convert 'PUT', 'DELETE' methods to 'POST' requests
$provide.decorator('$http', ['$delegate', 'ngx$httpTimeout', function($http, ngx$httpTimeout) {
// create function which overrides $http function
var _$http = $http;
$http = function (config) {
config.timeout = ngx$httpTimeout.config.timeout;
return _$http(config);
};
$http.pendingRequests = _$http.pendingRequests;
$http.defaults = _$http.defaults;
// code copied from angular.js $HttpProvider function
createShortMethods('get', 'delete', 'head', 'jsonp');
createShortMethodsWithData('post', 'put');
function createShortMethods(names) {
angular.forEach(arguments, function(name) {
$http[name] = function(url, config) {
return $http(angular.extend(config || {}, {
method : name,
url : url
}));
};
});
}
function createShortMethodsWithData(name) {
angular.forEach(arguments, function(name) {
$http[name] = function(url, data, config) {
return $http(angular.extend(config || {}, {
method : name,
url : url,
data : data
}));
};
});
}
return $http;
}]);
}]);
})();
Add dependency on the above module, and configure the timeout by configuring ngx$httpTimeoutProvider, like below:
angular.module('App', ['ngx$httpTimeoutModule']).config([ 'ngx$httpTimeoutProvider', function(ngx$httpTimeoutProvider) {
// config timeout for $http requests
ngx$httpTimeoutProvider.config.timeout = 300000; // 5min (5 min * 60 sec * 1000 millis)
} ]);

Resources