我有一个使用 Angular CLI 创建的 Angular 2 应用程序,它具有以下事件序列:
发生异步事件(例如用户单击按钮)。
1.1 触发动画。
1.2 运行一个昂贵的进程。这需要几秒钟。
UI 会根据昂贵过程的结果进行更新。
我遇到的问题是,当昂贵的进程运行时,动画和 UI 会冻结。
我制作了这个简化版本来显示问题:
http://plnkr.co/edit/13ieoXgMtaJfCq7Mijv7?p=preview
我尝试使用 NgZonerunOutsideAngular来运行昂贵的进程,但它与内联运行相同。我也尝试使用 Zone.js 库,但我不熟悉它,并且出现错误'zone.js.d.ts' is not a module
如何将这个昂贵的进程“分叉”到并行线程/区域中,然后在完成后将其合并到主区域中以优雅地更新 UI?或者任何合适的解决方案......它不必明确使用区域。
非常感谢!
我知道他们已经推荐了 Web Workers,但我没有看到任何具体提及 Angular Web Workers 的答案/评论。Web Workers 的唯一缺点是您不能在worker外部声明的方法/函数内部使用worker. 因此,如果您在昂贵的过程中使用库的方法,那么您就不能使用它。
如果情况并非如此,那么您就可以开始了:
更新:链接无效时包含的代码。这是一个简单的例子。
foo.worker.tsaddEventListener('message', ({ data }) => {
// Do some stuff
const response = 'This is the job result';
// This internal method 'postMessage' is used to return the result
postMessage(response);
});
Run Code Online (Sandbox Code Playgroud)
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.
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2447 次 |
| 最近记录: |