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.
Related
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
});
I am making a PWA where users can answer the forms. I want it to make also offline, so when a user fills out a form and does not have the internet connection, the reply will be uploaded when he is back online. For this, I want to catch the requests and send them when online. I wanted to base it on the following tutorial:
https://serviceworke.rs/request-deferrer_service-worker_doc.html
I have managed to implement the localStorage and ServiceWorker, but it seems the post messages are not caught correctly.
Here is the core function:
function tryOrFallback(fakeResponse) {
// Return a handler that...
return function(req, res) {
// If offline, enqueue and answer with the fake response.
if (!navigator.onLine) {
console.log('No network availability, enqueuing');
return;
// return enqueue(req).then(function() {
// // As the fake response will be reused but Response objects
// // are one use only, we need to clone it each time we use it.
// return fakeResponse.clone();
// });
}
console.log("LET'S FLUSH");
// If online, flush the queue and answer from network.
console.log('Network available! Flushing queue.');
return flushQueue().then(function() {
return fetch(req);
});
};
}
I use it with:
worker.post("mypath/add", tryOrFallback(new Response(null, {
status: 212,
body: JSON.stringify({
message: "HELLO"
}),
})));
The path is correct. It detects when the actual post event happens. However, I can't access the actual request (the one displayed in try or fallback "req" is basically empty) and the response, when displayed, has the custom status, but does not contain the message (the body is empty). So somehow I can detect when the POST is happening, but I can't get the actual message.
How to fix it?
Thank you in advance,
Grzegorz
Regarding your sample code, the way you're constructing your new Response is incorrect; you're supplying null for the response body. If you change it to the following, you're more likely to see what you're expecting:
new Response(JSON.stringify({message: "HELLO"}), {
status: 212,
});
But, for the use case you describe, I think the best solution would be to use the Background Sync API inside of your service worker. It will automatically take care of retrying your failed POST periodically.
Background Sync is currently only available in Chrome, so if you're concerned about that, or if you would prefer not to write all the code for it by hand, you could use the background sync library provided as part of the Workbox project. It will automatically fall back to explicit retries whenever the real Background Sync API isn't available.
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.
I need to use web sockets for some interactions with the user. I have pretty much copypasted solution from here - http://xsockets.net/blog/angular-js-xsocketsnet and got an issue with Firefox (27.0.1).
When I try to make this call (TwoWayBinding is my XSockets controller, I'm using .NET MVC on host side):
var connect = function (url) {
var deferred = $q.defer();
socket = new XSockets.WebSocket(url);
socket.on(XSockets.Events.open, function (conn) {
$rootScope.$apply(function () {
deferred.resolve(conn);
});
});
return deferred.promise;
};
connect("ws://localhost:49200/TwoWayBinding").then(function (ctx) {
isConnected = true;
queued.forEach(function (msg, i) {
publish(msg.t, msg.d);
});
queued = [];
});
I always get an error from Firebug:
Firefox can't establish a connection to the server at ws://localhost:49200/TwoWayBinding.
this.webSocket = new window.WebSocket(url, subprotocol || "XSocketsNET");
The same code works well in Chrome, it gets connected and I'm getting messages sent from host. Mentioned methods are wrapped into angular service, but this all works, I do not think this should be a problem.
One thing I was able to figure out from Fiddler was this:
Chrome:
Result Protocol Host URL Body Caching Content-Type Process Comments Custom
3 200 HTTP Tunnel to localhost:49200 0 chrome:3976
Result Protocol Host URL Body Caching Content-Type Process Comments Custom
6 101 HTTP localhost:49200 /TwoWayBinding?XSocketsClientStorageGuid=5cf5c99aafd141d1b247ed70107659e0 0 chrome:3976
Firefox:
Result Protocol Host URL Body Caching Content-Type Process Comments Custom
1740 200 HTTP Tunnel to localhost:49200 0 firefox:1420
Result Protocol Host URL Body Caching Content-Type Process Comments Custom
1741 - HTTP localhost:49200 /TwoWayBinding -1 firefox:1420
Simply said - there is some additional parameter XSocketsClientStorageGuid in the response for Chrome which does not occur in the respose to FF. I'm not sure if that has any impact or if I'm completely wrong but will appreciate any advice if somebody experiences same issue.
Update:
It looks like the critical line is this one
socket = new XSockets.WebSocket(url);
as the socket is not created properly in Firefox. But I still not have the cause of this.
What version are you running on , did you make a new installation of XSockets.NET using the Nuget Package or did you use the git example mentioned in the quesion above?
I just did a test on FF 26.0 and 27.0.1 , and it did go well using this pice of example;
http://xsockets.github.io/XSockets.JavaScript.API/test/index.html
I will have a look at the old Angular example asap and makre sure it is fixed of there is a problem!
Kind regards
Magnus
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);
};
});
});