[英]Angular lazy load module that only contains services?
I'm looking for a way to lazy load a module that doesn't contains any components but services only.我正在寻找一种方法来延迟加载不包含任何组件但仅包含服务的模块。 The background: in my app is an Excel export service using
exceljs
library.背景:在我的应用程序中是一个使用
exceljs
库的 Excel 导出服务。 This library is extremely large and I'm trying to prevent that the library will become part of vendor.js
or main.js
.这个库非常大,我试图防止该库成为
vendor.js
或main.js
的一部分。 It is "included" via import * as Excel from 'exceljs/dist/exceljs.min.js'
in a service.它通过
import * as Excel from 'exceljs/dist/exceljs.min.js'
在服务中“包含”。
Now I have several components in separate modules that make use of the "Excel export" service (no component).现在,我在使用“Excel 导出”服务的单独模块中有几个组件(无组件)。 I would prefer a method that the service is only loaded if the user is "clicking the export button" but not before.
我更喜欢仅在用户“单击导出按钮”而不是之前加载服务的方法。
How this can be done?如何做到这一点?
Here would be an approach:这将是一种方法:
@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))
})
}
}
The first time is loaded, m.loaded
will be false
.第一次加载时,
m.loaded
将为false
。 On subsequent times, it will be true
.在随后的时间里,这将是
true
。 With this, we can be sure that we don't load the module multiple times.有了这个,我们可以确定我们不会多次加载模块。
Of course, a easier (and probably better) approach will be to have a dedicated service for loading modules eg ModuleLoaderService
, where you'd have a Map
object keeping track of loaded modules.当然,更简单(并且可能更好)的方法是使用专门的服务来加载模块,例如
ModuleLoaderService
,您可以在其中使用Map
object 跟踪加载的模块。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.