我在Angular2应用程序中使用Web worker。当我从工作人员(onmessage
)触发的回调更新模型状态时,UI不会刷新。
我的理解是,该过程依赖于Zone.js猴子修补各种浏览器功能,以便能够检测来自XHR或超时(以及来自setTimeout
的状态更新)的更新。这应该包括对网络工作者的支持吗?我是否必须以某种方式明确触发更新?
答案 0 :(得分:1)
尝试使用NgZone并触发更新,如下所示:
zone.run(() => {
// the change detection will run after this function
});
答案 1 :(得分:0)
来自以下官方example的examples repo:
import {
UIMessageBus,
UIMessageBusSink,
UIMessageBusSource
} from "angular2/src/web-workers/ui/application";
var worker = new Worker("loader.js");
var bus = new UIMessageBus(new UIMessageBusSink(worker), new UIMessageBusSource(worker));
var VALUE = 5;
document.getElementById("send_echo")
.addEventListener("click", (e) => {
var val = (<HTMLInputElement>document.getElementById("echo_input")).value;
bus.sink.send({type: "echo", value: val});
});
bus.source.listen((message) => {
if (message.data.type === "echo_response") {
document.getElementById("echo_result").innerHTML =
`<span class='response'>${message.data.value}</span>`;
} else if (message.data.type === "test") {
bus.sink.send({type: "result", value: {id: message.data.id, value: VALUE}});
} else if (message.data.type == "result") {
document.getElementById("ui_result").innerHTML =
`<span class='result'>${message.data.value}</span>`;
} else if (message.data.type == "ready") {
bus.sink.send({type: "init"});
}
});