Search code examples
javascriptangulartypescriptweb-worker

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


I´m testing Web Workers and combining them with Angular 7+

This is my 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>

This is my 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 );
  }
}

This is my Webworker definition app.component.worker.js

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

All the files are at the same level.

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

When the local server runs, appears this message

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

I tried to set as relative path

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

But stills not working

What is wrong with my code? Does exists a best way to do all with Typescript?


Solution

  • I was also facing same issue with this code

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

    Change to

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

    After this I am not getting this issue with web worker.

    I am using this code on Angular 8.