如何通过延迟加载在模块之间共享组件

How to share components between modules with lazy loading

我正在使用延迟加载来加载我的模块。我处于需要在另一个模块中使用一种形式的模块的情况。

比如有产品模块和品牌模块。两者都以延迟加载方式加载。但我想让用户能够在产品表单中注册品牌。但我的问题是这两个模块都是延迟加载的。

我真的需要完全加载这两个模块吗?或者我可以只加载所需的组件吗?

我加载延迟加载:

const productRoutes: Routes = [
  {
    path: 'product',
    loadChildren: 'app/admin/product/product.module#ProductModule',
    canLoad: [AuthGuard]
  }
];

const brandRoutes: Routes = [
  {
    path: 'brand',
    loadChildren: 'app/admin/brand/brand.module#BrandModule',
    canLoad: [AuthGuard]
  }
];

我的组件:

....

<div class="form-group">
    <label for="exemplo">Create Name Product</label>
    <input type="text" name="name" [(ngModel)]="Product.name" #name="ngModel" >
</div>

<div class="form-group">
    <label for="exemplo">Create Brand</label>
    <brand-form-component></brand-form-component>
</div>

编辑

我创建了共享模块:

import { NgModule }            from '@angular/core';

import { FormComponent as 
    FormBrandComponent }      from '../../brand/brand-form/form.component'

@NgModule({
  imports:      [  ],
  declarations: [ FormBrandComponent ],
  providers:    [ FormBrandComponent ],
  exports:      [ FormBrandComponent ],
})
export class SharedModule { }

我在其他模块中导入:

品牌模块

import { SharedModule }from '../shared/shared.module';

@NgModule({
  imports: [ SharedModule, DialogModule, GrowlModule, Ng2PaginationModule, BrandRouting ],
  declarations: [ BrandComponent, ListComponent ],
  providers:[ BrandService ]
})
export class BrandModule {}

产品模块

import { SharedModule }from './shared/shared.module';


@NgModule({
  imports: [ SharedModule, CurrencyMaskModule, DragulaModule, GrowlModule, DialogModule, Ng2PaginationModule, productRouting, ReactiveFormsModule ],
  declarations: [ ProductComponent, FormComponent, ListComponent ],
  providers:[ FormComponent, ProductService, BreadService, MarcaService, GradeService ]
})
export class ProductModule { }

但是出现以下错误:

目前懒加载的实现是模块级别的,要么all or nothing。如果您需要在两者之间共享组件(听起来就是这样),那么您可能有一个尚未完全识别的隐藏共享模块。因此,您很有可能应该创建一个新模块来容纳那些共享的 components/services 并将该模块导入到其他两个延迟加载的模块中。

您可以选择新模块是延迟加载还是急切加载 - 两者都可以。 (由于它是产品和品牌模块的依赖项,一旦加载其中一个,新模块也会被加载)。