Angular Web Worker与轮询示例
当您在AngularJS中处理工作程序时,通常要求您的工作程序脚本是内联的(以防您使用诸如gulp / grunt之类的构建工具),我们可以使用以下方法来实现。
下面的示例还显示了如何使用worker对服务器进行轮询:
首先让我们创建我们的工人工厂:
module.factory("myWorker", function($q) {
var worker = undefined;
return {
startWork: function(postData) {
var defer = $q.defer();
if (worker) {
worker.terminate();
}
function workerFunction() {
var self = this;
self.onmessage = function(event) {
var timeoutPromise = undefined;
var dataUrl = event.data.dataUrl;
var pollingInterval = event.data.pollingInterval;
if (dataUrl) {
if (timeoutPromise) {
setTimeout.cancel(timeoutPromise);
}
console.log('Notifications - Data URL: ' + dataUrl);
var delay = 5000;
(function pollerFunc() {
timeoutPromise = setTimeout(function() {
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
var response = JSON.parse(xmlhttp.responseText);
self.postMessage(response.id);
pollerFunc();
}
};
xmlhttp.open('GET', dataUrl, true);
xmlhttp.send();
}, delay);
})();
}
}
}
var dataObj = '(' + workerFunction + ')();';
var blob = new Blob([dataObj.replace('"use strict";', '')]);
var blobURL = (window.URL ? URL : webkitURL).createObjectURL(blob, {
type: 'application/javascript; charset=utf-8'
});
worker = new Worker(blobURL);
worker.onmessage = function(e) {
console.log('Worker said: ', e.data);
defer.notify(e.data);
};
worker.postMessage(postData);
return defer.promise;
},
stopWork: function() {
if (worker) {
worker.terminate();
}
}
}
});
接下来,从我们的控制器呼叫工人工厂:
var inputToWorker = {
dataUrl: "http://jsonplaceholder.typicode.com/posts/1",
pollingInterval: 5
};
myWorker.startWork(inputToWorker).then(function(response) {
}, function(error) {
}, function(response) {
console.log("Notification worker RESPONSE: " + response);
});
您可以随时致电myWorker.stopWork();
从您的控制器终止工作人员!
已在IE11 +和FF及Chrome中测试