Bird
0
0

Why does this Angular Web Worker code fail?

medium📝 Debug Q7 of 15
Angular - Performance Optimization
Why does this Angular Web Worker code fail?
const worker = new Worker(new URL('./worker', import.meta.url));
worker.onmessage = (event) => console.log(event.data);
worker.postMessage();
Aonmessage must be assigned after postMessage is called.
BWorker file extension is missing, causing failure.
CpostMessage requires an argument; calling without one causes an error.
DWorker cannot be created with new URL syntax.
Step-by-Step Solution
Solution:
  1. Step 1: Check worker file path correctness

    The path './worker' lacks a file extension, which is required for Angular to locate the worker file.
  2. Step 2: Understand Angular worker file resolution

    Angular expects the worker file to have an extension like '.worker.ts' or '.worker.js' to process it correctly.
  3. Final Answer:

    Worker file extension is missing, causing failure. -> Option B
  4. Quick Check:

    Worker file must include extension for Angular to find it [OK]
Quick Trick: Always include file extension in worker URL [OK]
Common Mistakes:
  • Assuming postMessage can be called without arguments
  • Thinking onmessage order matters
  • Believing new URL syntax is invalid

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Angular Quizzes