I am developing an application and I have below requirement. from my angular application I am making REST call to server which will trigger some job on the server and return status as "Job Started". After that I want to keep checking status of job every 10 seconds, for which server provides API that return status of job.
Now my requirement is I need to call this job status API every 10 seconds, but in background, that means user should able to perform other tasks on application.
How would I achieve this?
Any help with some example would be really helpful.
You can resolve this by 2 way.
setInterval()
.Since it's only check if job is done via http
request it won't kill UI
and user will be able to perform other actions.
setInterval(() => {
this.http.post(...).subscribe(
(res) => handleResponse(res);
);
}, 10000);
With web workers there is a lot of trouble, depends how your project is build etc. However it will do the trick with background thread but there is a question. Is it only to make a http request to check some data is necessary for web worker?. If yes, then look at this link it's well explained how it works. You will have to create XHR
request since Angular
and jQuery
(I'm not 100% sure, but maybe there is ajax
for web workers) won't work there. The biggest trouble would be loading source code of web worker. You can stringify
source code of web worker (how to) or just build it as file and link it. It's depends how your project is gonna be build in production.
// source code for worker.
let code = function() {
setInterval(function() {
makeRequest()
.then(function(res) {
// process request. if you want to send message to main thread just use fn below
// message can be almost everything, but it can not pass any methods.
// self is simply worker. you don't have to declar self, it's already declared like window in main thread.
self.postMessage(message)
})
.catch(function(err) {
// process request failure.
})
}, 10000)
};
// stringify source code and make it blob as described in link
let worker = new Worker(code);
worker.addEventListener('message', function(workerReponse) {
// workerReponse is simply `message` which was passed in self.postMessage(message).
})
makeRequest method can look like this answer