使用 Angular 7+ 找不到 Web Worker 脚本的 URL

The URL to Web Worker script is not found with Angular 7+

我正在测试 Web Workers 并将它们与 Angular 7+

相结合

这是我的app.component.html

<div>
  <input type="text" name="lat" placeholder="Latitude" #lat (input)="updateMap( lat )">
  <input type="text" name="lng" placeholder="Longitude" #lng (input)="updateMap( lng )">
</div>

这是我的app.component.ts

import { Component, OnInit } from '@angular/core';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit {
  title = 'mapa';
  coords: any = {lat: 0, lng: 0};
  worker: Worker;

  ngOnInit() {
      this.worker = new Worker( './app.component.worker.js' );
  }

  updateMap( selector: any ) {
    const key   = selector.getAttribute('name');
    const value = Number(selector.value);
    this.coords[ key ] = value;

    this.worker.postMessage( this.coords );
  }
}

这是我的 Webworker 定义 app.component.worker.js

onmessage = ( e ) => {
    console.log( e );
};

所有文件都在同一级别。

project
 -e2e
 -node_modules
 -src
   -app
     -app-routing.module.ts
     -app.component.css
     -app.component.html
     -app.component.ts
     -app.component.worker.js
   -lot of files
 -lot of files

本地服务器运行时,出现此信息

GET http://localhost:4200/app.component.worker.js 404 (Not Found)

我尝试设置为相对路径

'./src/app/app.component.worker.js'

但还是不行

我的代码有什么问题? 是否存在使用 Typescript 完成所有操作的最佳方法?

这段代码也遇到了同样的问题

const worker = new Worker('./web-worker/messenger.worker');

改为

const worker = new Worker('./web-worker/messenger.worker', { type: `module` });

在此之后我没有遇到网络工作者的这个问题。

I am using this code on Angular 8.

对我来说,只需将路径 src/app/web-worker/messenger.worker.

然后尝试以下操作:

const worker = new Worker('src/app/web-worker/messenger.worker', { type: `module` });

别忘了运行:ng generate web-worker 然后重启 angular 服务,如果没有,它不会将你的 worker 文件编译成 webpack。