Ivy 有一个名为 的私有函数createInjector
,它在当前 API 中以 theta 形式公开,但稍后 Ivy 稳定后会公开。
假设你有这样的代码:
@NgModule({
declarations: [LazyComponent],
providers: [
{
provide: 'components',
useValue: {
lazy: LazyComponent
}
}
],
entryComponents: [LazyComponent]
})
export class LazyModule {
static getLazyComponents: () => { lazy: typeof LazyComponent };
constructor(injector: Injector) {
LazyModule.getLazyComponents = () => injector.get('components');
}
}
让我们延迟加载LazyModule
via 动态导入:
import { ɵcreateInjector as createInjector, Injector } from '@angular/core';
export class AppComponent {
constructor(injector: Injector) {
import('./lazy/lazy.module').then(({ LazyModule }) => {
createInjector(LazyModule, injector);
console.log(LazyModule.getLazyComponents());
});
}
}
但是使用这种方法 - 你懒加载一个模块。如果你想延迟加载组件 - 你可以在不使用模块LazyComponent
的情况下做到这一点,假设 this 位于lazy.component.ts
文件内:
@Component({
selector: 'app-lazy',
template: `
<h1>I am lazy</h1>
`
})
export class LazyComponent {}
您可以使用动态导入来加载此组件 +renderComponent
功能:
import { ɵrenderComponent as renderComponent, Injector } from '@angular/core';
@Component({
selector: 'app-root',
template: `
<app-lazy></app-lazy>
`
})
export class AppComponent {
constructor(injector: Injector) {
import('./lazy.component').then(({ LazyComponent }) => {
renderComponent(LazyComponent, {
injector,
host: 'app-lazy'
});
});
}
}
注意——惰性组件没有生命周期!constructor
将被调用,但不会像 等这样的ngOnInit
钩子ngOnDestroy
。
回到你关于惰性模块的问题 - 你可能想要公开那些惰性组件的组件工厂,就像这样:
export class LazyModule {
static getComponentFactories: () => {
lazy: ComponentFactory<LazyComponent>;
};
constructor(resolver: ComponentFactoryResolver) {
LazyModule.getComponentFactories = () => ({
lazy: resolver.resolveComponentFactory(LazyComponent)
});
}
}
如果不想使用静态函数,可以声明实例方法:
export class LazyModule {
constructor(private resolver: ComponentFactoryResolver) {}
public getComponentFactories() {
return {
lazy: this.resolver.resolveComponentFactory(LazyComponent)
};
}
}
然后得到这个模块的一个实例:
export class AppComponent {
constructor(private injector: Injector) {
import('./lazy/lazy.module').then(({ LazyModule }) => {
const injector = createInjector(LazyModule, this.injector);
const lazyModule = injector.get(LazyModule);
console.log(lazyModule.getComponentFactories());
});
}
}