web worker就是在web应用程序中使用的worker。这个worker是独立于web主线程的,在后台运行的线程。
web worker的优点就是可以将工作交给独立的其他线程去做,这样就不会阻塞主线程。
第一步:ng g webWorker webWorkerName 用于创建一个Worker 线程
在创建的woker文件中,编写你需要采用多线程做的事件,我这里是一个保存文件数据的功能
/// <reference lib="webworker" />
let startindex='';
let offset='';
let save_path='';
let curPatientId='';
// 用ng 命令会自动生成一个worker.ts文件
// 在worker.ts文件 监听事件
addEventListener('message',function(data) {
const response = `worker response to ${data}`;
startindex=data.data['startindex'];
offset=data.data["offset"];
save_path=data.data["path"];
curPatientId=data.data['curPatientId']
save_wavedata(startindex,offset,save_path,curPatientId)
});
let count=0
function save_wavedata(startindex,offset,save_path,curPatientId){
setInterval(() => {
// 在js中http协议的使用
let url = "http" + "://" + "127.0.0.1" + "/gin/history/wavedata";
console.log('save_wavedata',url);
var data1=new FormData();
data1.append( "start",startindex);
data1.append("patientid",curPatientId);
data1.append("path",save_path);
data1.append("offset",offset);
let content='';
const http=new XMLHttpRequest();
http.open('post',url,true);
http.send(data1);
http.οnlοad=function() {
// console.log('http1',http.responseText)
content=JSON.parse(http.responseText)
startindex=content["result"]['start'];
offset=content["result"]["offset"];
save_path=content["result"]["path"];
console.log('startindex2',startindex,offset,save_path,curPatientId)
// close()
// console.log('startindex3',startindex,offset,save_path,curPatientId)
}
},20000)
}
在angular文件中
//app.component.ts
import { Component,OnInit,OnDestroy } from '@angular/core';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.scss']
})
export class AppComponent implements OnInit,OnDestroy {
//定义一个worker
private worker?:Worker = undefined;
//向worker线程发送数据
getMessage(){
this.worker.postMessage({type:'get'});
}
ngOnInit(): void {
this.startWorker();
}
ngOnDestroy(): void {
this.stopWorker();
}
//新建线程
startWorker():void{
if(typeof Worker !== 'undefined'){
this.worker = new Worker('./webworker/count.worker',{ type: 'module' });//不加type会找不到文件
// 监听worker线程发送过来的数据
this.worker.onmessage = (event) =>{
console.log(event.data);
}
// 抓取worker线程的报错
this.worker.onerror = (error) =>{
console.error(error);
}
} else {
console.warn('do not support worker!');
}
}
stopWorker():void{
if(this.worker){
this.worker.postMessage({type:'stopAll'});
// 关闭主线程
this.worker.terminate();
this.worker = undefined;
}
}
}