nativescript worker ts想要服务变量

时间:2018-01-03 11:39:38

标签: multithreading sqlite nativescript web-worker

我正在使用nativescript创建本机应用程序。我有处理后台功能的情况(比如JAVA中的Thread)。我在google上进行了研究,我得到了nativescript worker,但在worker.ts中如何获得服务变量?

sync.component.ts

export class SyncComponent implements OnInit{
    worker: any;
    constructor(private router: Router, private sqliteService: SqliteService) {
        this.worker = new Worker("../../shared/worker/sync.worker");
        this.worker.onmessage = (msg) =>{
            console.log('data ',msg.data);
        }
        this.worker.onerror = (err) => {
            console.log("Sync Components");
            console.dir(err);
            this.worker.terminate();
        }

    ngOnInit() {
        this.page.actionBarHidden = true;
    }

    handleSyncNow() {
         this.worker.postMessage({msg: 'hi'});
    }
}

sync.worker.ts

require("globals");
var http = required('http');

onmessage = (msg)=> {

    console.log('in Worker onmessage: ',msg.data.msg);
    //var sqliteService = ;//How to get sqliteService variable Of SqliteService(ts) class
    //global.postMessage('hey this is from worker');

    handleSync();
};

onerror = (err) => {
    console.log(err);
}

function handleSync() {
     this.http.get(Config.apiUrl).map(response => response.json())
        .do(data => {
            console.log(data);
            console.log(data.message);
        });
}

sqlite.service.ts

@Injectable()
export class SqliteService {
    handleSyncData() {
        //Wrote required code
    }
}

我的问题:如何在handleSyncData()来自sqlite.service.ts' s sync.worker.ts函数中调用onmessage()函数?

1 个答案:

答案 0 :(得分:0)

你无法分享这样的变量。 SqliteService是一个包含一些内部句柄的对象,因此无法序列化。

您需要在工作人员中创建另一个实例并使用它。

想想这样,如果这是Java应用程序,共享SQL控制器的同一对象会导致错误 - 每个线程都需要它自己的数据库接口实例,它保存该线程的状态