How to pass variable from app.config() to app.run() - angularjs

I am loading data (idle time and timeout time) from the database via rest api call. From frontend side I am using AngularJs 1.3.1 $http get call to get the data.
I need the above data (idle time and timeout time) at the app.config() level --- which is working fine.
I need to pass the same data (idle time and timeout time) from app.config() to app.run(). Any idea how to do that?
Also how to make sure $http get call is completed and idle time and timeout time is fetched from the database before idle time and timeout time is sent to app.run()?
I hope people will understand the question and respond to it. I am stuck at it right now.
code block:
angular.module().config(function() {
var idleWarnTime, idleTimeOut;
var http = angular.injector([ 'ng' ]).get('$http');
http.get('timeout').success(function(response) {
idleWarnTime = response.data.warntime;
idleTimeOut = response.data.timeout;
}).error(function(error) {
console.log('session timeout details fetching from db failed');
});
});
angular.module().run(function() {
//need idleWarnTime and idleTimeOut values here and only after "timeout" rest api provide the result
});

Related

How to make request every 2 seconds with angular js and node js?

I have a server written with Nodejs that collects data. My client side is written with AngularJS. I need to create http request every two seconds to my server (setInterval) and display updated data. My server running 24/7. Can chrome block my requests if it reaches maximum? Can I implement another way, instead of create request from client side, maybe to push from my server?
Example of some request:
var indicesTimer = setInterval(getIndices,2000);
getIndices();
function getIndices(){
dataService.getIndices().then(function(res){
$scope.recentIndeces = res.data;
});
}
Check $interval service.
var stop = $interval(function() {
// Your code
}, 100);
With your code
var indicesTimer = $interval(getIndices,2000);
getIndices();
function getIndices(){
dataService.getIndices().then(function(res){
$scope.recentIndeces = res.data;
});
}
You can use websocket. By using that, your server can notify your client in case something changed in the server side so you don't have to do a polling (polling is what you do when sending request every x seconds). Take a look at socket.io
This is the typically behavior of a heartbeat. Chrome or any other browser does not block requests.
As long as your setInterval() handler doesn't run forever, it won't block other things from eventually running.

Don't execute a $resource request in angular when there is already a request running

I use a interval of 10 seconds for sending a request to get the most recent data:
var pollInterval = 10000;
var poll;
poll= $interval(function()
{
getNewestData();//$resource factory to get server data
}, pollInterval );
This works fine voor 99% of the time, but if the internet speed is really slow(I have actually experienced this), It will send the next request before the current is finished. Is there a way to just skip the current interval request if the previous one is still busy? Obsiously I could just use booleans to keep the state of the request, but I wonder if there is a better(native to angular) way of doing this?
Use the $resolved property of the Resource object to check if the previous operation is done.
From the Docs:
The Resource instances and collections have these additional properties:
$promise: the promise of the original server interaction that created this instance or collection.
$resolved: true after first server interaction is completed (either with success or rejection), false before that. Knowing if the Resource has been resolved is useful in data-binding.
$cancelRequest: If there is a cancellable, pending request related to the instance or collection, calling this method will abort the request.
-- AngularJS ngResource $resource API Reference.
How about making the request, then waiting for that to complete and then wait 10 seconds before making the same request again? Something along this line:
var pollInterval = 10000;
var getNewestData = function () {
// returns data in promise using $http, $resource or some other way
};
var getNewestDataContinuously = function () {
getNewestData().then(function (data) {
// do something with the data
$timeout(function () {
getNewestDataContinuously();
}, pollInterval);
});
};
getNewestData is the function that actually makes the request and returns the data in a promise.
And once data is fetched, a $timeout is started with timer as 10 seconds which then repeats the process.

Intervals on a server

I have recently bought a lifx lamp (a light you can control with http request to change the color) and I would like to make a website as a remote to make a cycle color.
For example, I am on the website, I click on the button cycle 1, each seconds, with a $interval() (setInterval()), Angular send a HTTP request to the lamp and that work.
However, I'd like to know how can a make this job (send a request each seconds) on the server with a back-end language.
I wonder if angular send a request to a PHP page with the intervals will work.
Otherwise, (I'm a newbie in AngularJS) is there a way to to this job with angular but in server side.
If I really want to do that in server side, it's because I would like that the cycle continues even if I shut down the computer (client side)
Ask if you need more information
Thank you and sorry for my aweful English
If you just want to write a server-side script for this, you don't need Angular. Consider using NodeJS and the request module.
Something like this should work:
var request = require('request');
var interval = 1000; // 1 second, in milliseconds
function changeColor() {
/* some code to pick a random color */
request('http://url-for-lifx-api.com', function (error, response, body) {
if (!error && response.statusCode === 200) {
setTimeout(changeColor, interval);
} else {
/* handle error */
}
});
}
changeColor();
NOTE: You will need to modify the request to use the proper HTTP method (GET, PUT, POST) and, if necessary, pass headers or a body with the request.

angularjs $http cache, will it cache server errors

In angular $http.get(url, {cache:true}) will nicely cache server responses. But what does the cache do when the GET request to the server fails? This could be a temporary connection issue or a server response like a timeout.
Suppose I handle the error and display a retry button, will a subsequent call to $http.get(url, {cache:true}) retry the server or will it give me a failed promise from the cache?
If multiple requests are made to the same GET url the cache will cause there to only be one request. Quoting the documentation:
If there are multiple GET requests for the same URL that should be cached using the same cache, but the cache is not populated yet, only one request to the server will be made and the remaining requests will be fulfilled using the response from the first request.
However, when that request returns if the status code is not successful it will not be cached (it will be removed from the cache).
We can see this in the source code:
/**
* Callback registered to $httpBackend():
* - caches the response if desired
* - resolves the raw $http promise
* - calls $apply
*/
function done(status, response, headersString, statusText) {
if (cache) {
if (isSuccess(status)) {
cache.put(url, [status, response, parseHeaders(headersString), statusText]);
} else {
// remove promise from the cache
cache.remove(url);
}
}
So in short - Angular will not cached 'failed' requests - that is: requests with a non-success status code.

Get HTTP request time in angular.js?

I am trying to get the duration of each HTTP request I send through Angular.js, to so I can send it to New Relic analytics. I can use transformRequest to find when any HTTP request is fired, and I can use responseInterceptors to get the completed request. But I can't find any way to link that information together.
Any suggestions to get the duration of HTTP requests? Ideally something that works with Angularjs Rails Resource: https://github.com/FineLinePrototyping/angularjs-rails-resource?
I got this code from one of the blogs for rendering overlays by default when an http request is made. I modified it a little bit to address your issue. See if this helps.
angular
.module('analytics', [])
.config(function($httpProvider) {
$httpProvider.responseInterceptors.push(function() {
return function(promise) {
// START YOUR TIMER
var callReturn = function(r) {
// END YOUR TIMER
total_time = START TIMER - END TIMER
};
return promise.then(callReturn, callReturn);
};
});
});

Resources