0
我有factory
,我想用Web Worker
爲angularJs(lib from here)網絡中使用工作者的角度服務
var appServices= angular.module('appServices', ['ngResource', 'ngWebworker']);
appServices.factory('CurrentUserData', [
'apiPath', '$resource', '$rootScope', 'Auth','Webworker',
function (apiPath, $resource, $rootScope, Auth, Webworker) {
var requests = $resource(apiPath + "/Requests", {});
var pendingRequests = $resource(apiPath + "/RequestRecipient/Pending", {});
var requestResources = [];
var pendingRequestResources = [];
var updateResources = function(resource, newResource) {
if (angular.isArray(resource)) {
resource.length = 0;
for (var i = 0; i < newResource.length; ++i) {
resource.push(newResource[i]);
}
} else {
for (var key in resource) {
delete resource[key];
}
for (var key in newResource) {
resource[key] = newResource[key];
}
}
};
var fetchResources = function(){
user = Auth.getCurrentUser();
if(!user){
return;
}
requests.query(function (requestResponse) {
updateResources(requestResources, requestResponse);
});
pendingRequests.query(function (requestResponse) {
updateResources(pendingRequestResources, requestResponse);
});
};
fetchResources();
setInterval(fetchResources, 120000); // Here I want to use Worker, which can Update requestResources and pendingRequestResources in "new thread"
return {
'requests': function() {
return requestResources;
},
'pendingRequests': function() {
return pendingRequestResources;
}
}
我試圖用網絡工作者在接下來的方式:
fetchResources();//init arrays
if (window.Worker) { // Check if Browser supports the Worker api.
var myWorker = Webworker.create(setInterval);
myWorker.run(fetchResources, 120000).then(function(result) {
console.log("done");
});
} else {
setInterval(fetchResources, 120000);
}
上啓動我的陣列然後在網絡工作者更新他們每120000毫秒,但我得到錯誤:
angular.js:11655 Error: Failed to execute 'postMessage' on 'Worker': An object could not be cloned.
所以我認爲這是我的custon服務的問題,我使用的是函數,它傳遞給了網絡工作者。
問題是您傳遞的是函數而不是數據。作爲Web工作者的'setInterval'沒有任何意義,它應該在worker中調用。 – zeroflagL
調用'postMessage'在哪裏?在你發佈的所有代碼中,我沒有看到任何'postMessage'方法... – Wilt
@Wilt,請檢查我使用的庫的「文檔」http://mattslocum.github.io/ng-webworker/我想我做了文檔中描述的所有內容。 – demo