1

我已经开始在 Angular 9 中使用新的延迟加载组件。我有一个使用 NGXS 的有状态组件,其状态被延迟加载到组件附近的模块中,但是一旦组件呈现,存储不会更新为新状态。

功能模块

@NgModule({
  imports: [
    NgxsModule.forFeature([PurchaseState]),
    SharedModule, 
    FormsModule, 
    GridModule,
    PurchasesApiModule,
    SidePanelCoreModule
  ],
  declarations: [PurchaseDetailsPageComponent, PurchaseDetailsFormComponent, PurchaseDetailsAllotmentListComponent],
})
export class PurchaseDetailsModule {
  constructor() {
    console.log('PURCHASE CONSTRUCTED')
  }
}

动态组件加载器

  async getComponent(key: string) {
    const lazyComp = await import('@pe/purchase-details').then(c => c.PurchaseDetailsPageComponent);
    const factory = this.componentFactoryResolver.resolveComponentFactory(lazyComp);
    this._component = this.content.createComponent(factory, null, this.injector);
  }

诸如GridModule(仅在此处声明)之类的东西可以正常工作,但是我猜模块加载的提供程序部分没有运行?

有没有人遇到过这样的事情?

我尝试在本文中描述的组件 .ts 文件中包含状态的模块声明,但没有骰子:(

4

1 回答 1

1

因此,在查看了角度路由器延迟加载模块的方式后,我能够拼凑出一个解决方案。

我在应用级服务中管理配置缓存,并使用这个人动态加载内容。

很高兴听到更好的解决方案:)

@Component({
  selector: 'app-lazy',
  templateUrl: './app-lazy.component.html',
  styleUrls: ['./app-lazy.component.scss'],
})
export class StatefulLazyComponent implements OnInit, OnDestroy {

  @ViewChild('content', { read: ViewContainerRef, static: true }) content: ViewContainerRef;
  _lazyLoadSub: Subscription;
  constructor(
    private componentFactoryResolver: ComponentFactoryResolver,
    private injector: Injector,
    private compiler: Compiler,
  ) {}

  ngOnInit() {
    const config  = {
      component: import('@pe/purchase-details').then(c => c.PurchaseDetailsPageComponent),
      module: import('@pe/purchase-details').then(m => m.PurchaseDetailsModule)
    };

    this._lazyLoadSub = combineLatest([
      this.getComponentObs(config.component),
      this.getModuleFactory(config.module)
      ]).subscribe(data => {
      const [compFactory, moduleFactory] = data;
      const module = moduleFactory.create(this.injector);
      const component = this.content.createComponent(compFactory, null, this.injector);
      // Module and component are loaded can now do stuff with them
    });
  }

  ngOnDestroy() {
    if(this._lazyLoadSub) {
      this._lazyLoadSub.unsubscribe();
    }
  }

  getComponentObs(promise: Promise<Type<any>>): Observable<ComponentFactory<any>> {
    return from(promise).pipe(mergeMap(comp => of(this.componentFactoryResolver.resolveComponentFactory<any>(comp))));
  }

  getModuleFactory(promise: Promise<Type<any>>): Observable<NgModuleFactory<any>> {
      return from(promise).pipe(mergeMap(t => from(this.compiler.compileModuleAsync(t))));
  }
}
于 2020-02-13T02:49:39.323 回答