addEventListener('message', async ({ data }) => { if (data) { const theMessage = data as WorkerMessage; const theData = theMessage.data; const theAction = theMessage.action;
let responseMessage: WorkerMessage; if (theAction === WorkerAction.FetchCheckpoints) { const tagID = +theData; if (typeof tagID !== 'number') { // throw new Error('tagID should be number'); return postMessage(newError('tagID should be number')); } const responseData = await fetchCheckpointsByTag(+theData); responseMessage = new WorkerMessage(responseData, theAction); } else { // if (action === WorkerAction.Ping) const content = (theData || '').split('').sort().join(''); responseMessage = new WorkerMessage(content, theAction); } return postMessage(responseMessage); } else { console.error('data of MessageEvent is empty'); } });
/// localStorage is not available in web worker // https://developer.mozilla.org/en-US/docs/Web/API/Web_Workers_API/Functions_and_classes_available_to_workers /** caching */ const __STORAGE__ = new Map<string, any>();
/** generate key for localStorage */ const genStorageKey = (...parameters) => { // arguments.callee is also not availabe in web worker return (parameters || []).join(':'); };
ngOnInit(): void { // register web worker if (typeof Worker !== 'undefined') { this.webWorker = new Worker('../xxxx.worker', { type: 'module' }); this.webWorker.addEventListener('message', ({ data }) => { const theMessage = data as WorkerMessage; const theAction = theMessage.action; if (theAction === WorkerAction.FetchCheckpoints) { this.qwCheckPoints.response.Data = theMessage.data || []; this.qwCheckPoints.status = Utility.isNotEmptyArray(this.qwCheckPoints.response.Data) ? QueryStatus.SUCCESS : QueryStatus.EMPTY; } }); this.webWorker.postMessage(new WorkerMessage(null, WorkerAction.FetchCheckpoints)); } else { // Web workers are not supported in this environment. // TODO: You should add a fallback so that your program still executes correctly. console.log('The browser doesn\'t support Web Worker.'); } }