Angular2 Web Worker - 视图未更新

时间:2016-12-24 23:19:31

标签: angular typescript web-worker

我创建了一个实现Worker()对象的组件来生成大量的随机数。我听到生成单个随机数后触发的Worker() onmessage事件。 Onmessage事件处理程序更改组件模型(在控制台中检查),但视图未更新。

尝试NgZoneChangeDetectionRef,但没有运气。我很感激帮助,因为我已经坚持了好几天。

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);
    }
}

0 个答案:

没有答案