Reputation: 11228
I wish to have a progress bar on the client-side built using AngularJS. This progress bar will inform the end-user of the current state of execution of a query on the server.
The server, in this case, is ExpressJS.
So, using AngularJS I will make a request to the server such as:
$http.post('/data/aPath')
.success(function (result){
//Update the progress here.
});
What I wish to know is how can I send responses without ending them so that AngularJS can receive them as shown above and I can update the progress bar? That is, on the Node.js side,
app.post('/data/aPath', function (request, response){
//What should I do here to update the client on the
//current execution state
//Something on the lines of
//response.write("finished fetching user details, moving on to
//updating records"
});
so that the client can then update the progress bar?
Upvotes: 3
Views: 5400
Reputation: 5981
I haven't done this myself, to be honest, but I believe one way to approach this would be like this:
On your client-side, modify your $http.post
function
function getStatusFromProcessing() {
$http.post('/data/aPath').success(function (result){
// Pseudocode:
if(result.status is something) { // ex: (result >= 20)
// update progressbar with new value
}
if(result.status is somethingElse) { // ex: (result >= 40)
// update progressbar with new value
}
// All updating of progressbar done for now
if(result.status !== 100) { // Progress is not done
return getStatusFromProcessing(); // run the function again
} else {
return; // All done, move on
}
});
}
Now, the server side:
app.post('/data/aPath', function (request, response){
// You need some kind of function/service, which returns
// the current state of the processing.
var currentStatus = getStatusFromRunningProcess();
// getStatusFromRunningProcess() should return a value between (0 - 100)
return response.json({ status: currentStatus});
});
A few notes:
if(result.status !== 100)
of a couple of (hundred) milliseconds to avoid spamming the http request. But that is fine-tuning :)Update, alternative solution using sockets
If you don't want to make several requests to the server from the client, you can switch it around; the server sends a message to the client when the process is updated. This requires more likely less bandwidth and requests done to the server. This method is possible using sockets.
When using sockets, the socket.io framework is very popular. There are also lots of tutorials online.
In short:
Here is a SO post regarding sockets and a progress bar. This is about file uploads though, but the concept is the same.
Upvotes: 2