我有一个Web工作者,他的工作是定期轮询Web服务以获取数据,然后将该数据插入到IndexedDB数据库中。
是否有任何建议的方法通知AngularJS模块更新对象存储,因为所有更改都发生在Angular之外?
答案 0 :(得分:2)
当您的网络工作人员完成时,调用$ scope。$ apply()。您将需要获取引导ng-app的“root”元素。例如:
HTML:
<div id="rootElement" ng-app="myApp">
...
</div>
JavaScript的:
//Call $apply() to start an angular digest cycle where any updates you made to objects
//angular knows about will update the view.
angular.element(document.getElementById("rootElement")).scope().$apply();
修改:包括示例onmessage订阅。
由于您的工作人员只写入IndexedDb,您还需要使用postMessage将数据恢复为HTML(和角度)。例如,在您的HTML中:
var worker = new Worker("pathToWorker.js");
//Start worker in some way
worker.postMessage();
//Use data from the worker to update scope.
worker.addEventListener("message", function (e) {
//Get the data from the worker
var indexData = e.data;
//Update a scope variable (scopevar)
//Note: The element you query with angular.element must have the scope variable you
//are interested in.
angular.element(document.getElementById("MainController")).scope().$apply('scopevar=' + JSON.stringify(indexData));
}, false);
来自你的工人:
self.addEventListener("message", function (e) {
//Do work to write to IndexedDb
//PostMessage using the indexDb Data so angular can know about it.
self.postMessage({title: "Foo", data: "Bar"});
}
在没有看到你的代码的情况下,我无法给出一个更具体的例子,但是来自worker的postMessage绝对是将你的工作者的数据恢复到有角度的方式。