简体   繁体   中英

Angular: Export Components from Lazy Loaded Module

  1. AppModule :

    • has ShellModule as lazy load
  2. ShellModule :

    • import SharableModule
      • use SharableComponent
    • has FooModule as lazy load

SharableModule :

  • export SharableComponent
  • provide SharableService
  1. FooModule :

    • routing FooComponent OR BarComponent
  2. FooComponent , BarComponent

    • use ShareableComponent

Does not work SharableModule.exports with lazy load, So can not use SharableComponent in FooModule

is that right?

I added Components List of SharableModule to FooModule then work right.

but occured error, because declared on 2 modules( ShellModule , FooModule ).

but ShellModule Components required SharableModule Features like FooModule

have anything right way?

It is addressed quite comprehensively at the docs .

Generally, you should have shared.module where you can import/export all your shareable component/directive, other modules. And it will be import in any lazy-loading modules you want to use it.

For services , generally they should be singleton (single instance) for your whole application to use. Therefore, they should be grouped in so-called core.module and this module will be imported in your root.module (aka. app.module`).

Any feature modules should be lazy-loading modules.

The project structure is something like this:

+--app
    |
    +--core.module/
    |   |
    |   +--(import your sevices here...)
    |
    +--shared.module
    |   |
    |   +--(import/export all your components/directives/modules here)
    |
    +--any-lazy-loading.module
    |   |
    |   +--(import shared-module here)
    |
    app.module
        |
        +--(import core.module here)

Do not use SharableModule to provide SharableService as each lazy loaded module that imports the service will end up with different instance of the service. If you need to use all those services as singleton then add them to core module. You can also create a separate core-service.module. Use Sharable Module to just share components or directives.

You can do this

core-components.module.ts[ Add core components]
core-services.module.ts[ Add all shared services]
shared.module.ts [ this module exports all shared component and modules]

In the shell.module.ts import the SharedModule ie shared.module In the foo.module import the SharedModule ie shared.module Similarly you can add as many modules[ lazy loaded or non lazy loaded] with just SharedModule imported as the common module.

This will prevent any cyclic dependencies and let you share the common components across the app modules.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM