angular - 在 Angular 2 中运行昂贵的任务而不阻塞 UI

标签 angular

我有一个使用 Angular CLI 创建的 Angular 2 应用程序,它具有以下事件序列:

  • 发生异步事件(例如,用户单击按钮)。

    1.1 触发动画。

    1.2 运行一个昂贵的过程。这需要几秒钟。
  • UI 会根据昂贵的过程的结果进行更新。

  • 我遇到的问题是动画和 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 之外声明的方法/函数.因此,例如,如果您在繁重昂贵的过程中使用库的方法,那么您就不能使用它。
    如果不是这种情况,那么你很高兴:

  • 官方文档(非常基本且简短):https://angular.io/guide/web-worker
  • 非常有用的教程(更多扩展):https://blog.logrocket.com/how-to-execute-a-function-with-a-web-worker-on-a-different-thread-in-angular/

  • 更新:链接失效时包含的代码。这是一个简单的例子。
  • 创建一个名为 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);
    });
    
  • 使用另一个文件中的 worker :

  • 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/

    相关文章:

    c# - 如何将文件从 Angular 上传到 ASP.NET Core Web API

    javascript - 为什么 first() rxjs 运算符不断返回数组

    angular - 测试 - stub 服务方法未定义

    angular - 检查是否以 "ionic serve"运行以在程序中使用条件

    angular - ASP .Net Core 与 Razor Pages 对比 Angular for UI

    html - 列表组不会在 Angular 递归列表中显示为子列表

    angular - 创建一个可以在 Angular 4 模板中使用的全局函数

    Angular 2翻译在应用程序中更改语言

    node.js - 平均堆栈 : can't display data from a single Mongodb element by it's id

    angular - 什么相当于 Angular 2+ 中的 Vue 的 Vuex?