有點遲到的答案,但也許它可以幫助別人。 看看https://www.javascripttuts.com/how-to-use-web-workers-with-ionic-in-one-go/
我跟着那篇文章,但不得不做一些調整,因爲我不得不調用一個工作方法的需求,而不是構造函數。
在./src/assets
文件夾中創建一個名爲workers的新文件夾,其中您的工作人員爲。 JS文件將生存。是的JS不是TS,據我所知,TypeScript文件不會編譯成可用的webworker。
創建一個webworker。我會貼上我fuzzySearch webworker的主要代碼(./assets/workers/fuzzysearch-worker.js
):
'use strict';
var pattern, originalList;
self.onmessage = function(event) {
// Receive a message and answer accordingly
pattern = event.data.pattern;
originalList = event.data.originalList;
self.doFuzzySearch();
};
self.doFuzzySearch = function() {
var filteredList;
console.time('internalFastFilter');
filteredList = self.fastFilter(originalList, (item) => self.hasApproxPattern(item.searchField, pattern));
console.timeEnd('internalFastFilter');
// Send the results back
postMessage({ filteredList: filteredList });
};
// The code above is purposely incomplete
在你的。 TS文件中聲明工人變量(一般是上面的構造函數):
private readonly searchWorker: Worker = new Worker('./assets/workers/fuzzysearch-worker.js');
在構造函數:
constructor(/* Other injected dependencies here */
public ngZone: NgZone) {
this.searchWorker.onmessage = (event) => {
// Inside ngZone for proper ChangeDetection
this.ngZone.run(()=> {
this.dataList = event.data.filteredList;
console.timeEnd('searchWorker');
})
};
}
最後,在你的 「動作功能」,可以說doSearch
:
doSearch(event) {
// ... extra code to do some magic
console.time('searchWorker');
this.searchWorker.postMessage({ command: 'doFuzzySearch', originalList: this.realList, pattern: searchFilter });
// ... extra code to do some other magic
}
this.searchWorker.postMessage
撥打電話。所有重載操作都在webworker內解決。
希望它有幫助。 此致敬禮。