我有一个使用 Angular CLI 创建的 Angular 2 应用程序,它具有以下事件序列:
1.1 触发动画。
1.2 运行一个昂贵的过程。这需要几秒钟。
我遇到的问题是动画和 UI 在昂贵的进程运行时卡住。
我制作了这个显示问题的简化版本:
http://plnkr.co/edit/13ieoXgMtaJfCq7Mijv7?p=preview
我尝试使用 NgZone 的
runOutsideAngular
运行昂贵的进程,但它与内联运行相同。我也试过使用 Zone.js 库,但我不熟悉它,而且我收到错误 'zone.js.d.ts' is not a module
如何将这个昂贵的进程“ fork ”到一个并行线程/区域中,然后在完成优雅地更新 UI 后将其合并到主区域中?或者任何合适的解决方案......它不必明确使用区域。
谢谢一堆!
最佳答案
我知道他们已经推荐了 Web Workers,但我没有看到任何具体提到 Angular Web Workers 的答案/评论。 Web Workers 的唯一缺点是你不能在 worker
内部使用在 worker
之外声明的方法/函数.因此,例如,如果您在繁重昂贵的过程中使用库的方法,那么您就不能使用它。
如果不是这种情况,那么你很高兴:
更新:链接失效时包含的代码。这是一个简单的例子。
foo.worker.ts
的文件addEventListener('message', ({ data }) => {
// Do some stuff
const response = 'This is the job result';
// This internal method 'postMessage' is used to return the result
postMessage(response);
});
const worker = new Worker('./foo.worker', { type: 'module' });
worker.onmessage = ({ data }) => {
// This will get executed when the worker is finished and
// calls 'postMessage'.
// 'data' object is the result that is returned from the worker.
};
// This is what you call to initiate the worker process.
// As a parameter you will send the info that the worker needs
// to do its job (In this case, 'hello').
worker.postMessage('hello');
} else {
// Web workers are not supported in this environment.
// You should add a fallback so that your program still executes correctly.
}
关于angular - 在 Angular 2 中运行昂贵的任务而不阻塞 UI,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38859458/