[英]Angular lazy load module that only contains services?
我正在尋找一種方法來延遲加載不包含任何組件但僅包含服務的模塊。 背景:在我的應用程序中是一個使用exceljs
庫的 Excel 導出服務。 這個庫非常大,我試圖防止該庫成為vendor.js
或main.js
的一部分。 它通過import * as Excel from 'exceljs/dist/exceljs.min.js'
在服務中“包含”。
現在,我在使用“Excel 導出”服務的單獨模塊中有幾個組件(無組件)。 我更喜歡僅在用戶“單擊導出按鈕”而不是之前加載服務的方法。
如何做到這一點?
這將是一種方法:
@NgModule({
declarations: [],
imports: [
CommonModule
],
providers: [ExcelService]
})
export class ExcelModule {
static loaded = false;
}
export class AppComponent {
constructor (
private compiler: Compiler,
private injector: Injector
) { }
load () {
import('./excel/excel.module')
.then(m => m.ExcelModule)
.then(m => {
console.dir(m.loaded)
return m;
})
.then(m => this.compiler.compileModuleAsync(m).then(r => (m.loaded = true,r)))
.then(factory => {
const module = factory.create(this.injector);
console.dir(module.injector.get(ExcelService))
})
}
}
第一次加載時, m.loaded
將為false
。 在隨后的時間里,這將是true
。 有了這個,我們可以確定我們不會多次加載模塊。
當然,更簡單(並且可能更好)的方法是使用專門的服務來加載模塊,例如ModuleLoaderService
,您可以在其中使用Map
object 跟蹤加載的模塊。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.