如何在angular中使用web worker(ngx web worker)?

如何在angular中使用web worker(ngx web worker)?,angular,diff,web-worker,Angular,Diff,Web Worker,我想区分两个大文本,所以我决定使用diffjs()。不幸的是,它对于javascript进程来说太重了,使得页面在超过15秒的时间里毫无用处 我有一个angular应用程序,所以我决定试用NGXWebWorker(),可能会有所帮助。最后,我可能不理解web workers的这个实现,因为它没有运行( 最简单的例子: import * as diff from 'diff'; import { WebWorkerService } from 'ngx-web-worker'; @Compone

我想区分两个大文本,所以我决定使用diffjs()。不幸的是,它对于javascript进程来说太重了,使得页面在超过15秒的时间里毫无用处

我有一个angular应用程序,所以我决定试用NGXWebWorker(),可能会有所帮助。最后,我可能不理解web workers的这个实现,因为它没有运行(

最简单的例子:

import * as diff from 'diff';
import { WebWorkerService } from 'ngx-web-worker';

@Component({...}) ... {
  constructor(
    private _webWorker: WebWorkerService
  ){}
  ...
  ngOnInit() {
        this._webWorker.run(diff.diffTrimmedLines, this.texts).then((result) => {
          let changes:number = 0;
          result.forEach((part) => {
            if(part.added || part.removed){ changes++; }
          });
          console.log(changes);
        });
  }
}

感谢您的帮助和提前的时间。:)

我在angular.json中的资产中添加了以下内容:

{ "glob": "diff.min.js", "input": "node_modules/diff/dist", "output": "assets/js"}
这样,我将在生成后在我的资产文件夹中获取脚本。接下来,我更改了代码:

this._webWorker.run((input:any) => { 
   importScripts(`${input.protocol}//${input.host}/path/assets/js/diff.min.js`);
   return Diff.diffTrimmedLines(input.texts[0], input.texts[1]);
 }, {
    texts: texts,
    protocol: window.location.protocol,
    host: window.location.host
 }).then(...);
因此,使用importScripts,我可以从资产中加载js


希望这对其他人有帮助:)

我在angular.json中的资产中添加了这一点:

{ "glob": "diff.min.js", "input": "node_modules/diff/dist", "output": "assets/js"}
这样,我将在生成后在我的资产文件夹中获取脚本。接下来,我更改了代码:

this._webWorker.run((input:any) => { 
   importScripts(`${input.protocol}//${input.host}/path/assets/js/diff.min.js`);
   return Diff.diffTrimmedLines(input.texts[0], input.texts[1]);
 }, {
    texts: texts,
    protocol: window.location.protocol,
    host: window.location.host
 }).then(...);
因此,使用importScripts,我可以从资产中加载js

希望这对其他人有帮助:)

要将web worker添加到现有项目,请使用Angular CLI ng generate命令

ng generate web-worker <location>

要将web worker添加到现有项目,请使用Angular CLI ng generate命令

ng generate web-worker <location>

是diff.diff纯函数;没有任何依赖关系。方法中不应该有任何实例或插件依赖项。类似于u.find()或angular Functionty的东西我在和处找到了代码,但据我所见,它不使用任何依赖项,因此应该可以工作。Ok。似乎有什么是因为我得到了这个错误:“未捕获的引用错误:diff_uuwebpack_uimported_umodule_u16_uu未定义”您可以使用@angular/service worker()。是diff.diffTrimmedLines纯函数;没有任何依赖关系。方法中不应该有任何实例或插件依赖项。类似于u.find()或angular Functionty的东西我在和处找到了代码,但据我所见,它不使用任何依赖项,因此应该可以工作。Ok。似乎有什么是因为我得到了这个错误:“未捕获的引用错误:diff\uu WEBPACK\u IMPORTED\u MODULE\u 16\uu未定义”您可以使用@angular/service worker()。