我创建了一个实现Worker()对象的组件来生成大量的随机数。我听到生成单个随机数后触发的Worker() onmessage
事件。 Onmessage
事件处理程序更改组件模型(在控制台中检查),但视图未更新。
尝试NgZone
,ChangeDetectionRef
,但没有运气。我很感激帮助,因为我已经坚持了好几天。
import { Component, OnInit, OnChanges, NgZone, Input,ChangeDetectorRef }from '@angular/core';
@Component({
selector: 'my-app',
template: `<h1>Counter :{{counter}}</h1>`,
})
export class AppComponent implements OnInit{
private counter: number = 0;
constructor(private cd: ChangeDetectorRef){}
private _webWorker: Worker;
ngOnInit(){
var blobURL = URL.createObjectURL(new Blob([
"onmessage = function (val) { for (var x = 0; x < val.data; x++) { postMessage( Math.random() ) } };"
], { type: 'application/javascript' }));
this._webWorker = new Worker(blobURL);
this._webWorker.addEventListener('message', (val) => {
console.log("Returned form webworker..." + val.data);
this.counter = val.data;
this.cd.markForCheck(); //also not working with NgZone.run()
});
this._webWorker.postMessage(100);
}
}