简体   繁体   中英

Eagerly loaded module - Imported or Exported in core module?

In order to make my AppModule cleaner, I imported an eagerly loaded feature module in the CoreModule, which is imported (once) in the AppModule.

What i've found interesting, is that the app works by either exporting or importing the feature module in the CoreModule. Can anyone explain the difference? What's the correct way?

Well, if there's a feature(mostly a declarable like a Component, Directive or Pipe) that you have in that FeatureModule and you want to use it in your CoreModule (which you've imported in your AppModule ) or AppModule , you'll have to export it from your CoreModule as well.

If you export something from a Module it would be available to use in a Module that you import that Module in.

And if you export that module from the module that you've imported it in, you'll be able to use the exported module's features in the module that you're importing this module in.

Let's take for eg, an example with a CoreModule , an AppModule and a FeatureModule .

The FeatureModule has a FeatureComponent that's declared in it. If you want to use this FeatureComponent in the CoreModule , you'll have to export the FeatureComponent from the FeatureModule and then import the FeatureModule in your CoreModule .

Now if you want to use the FeatureCompoent in your AppModule as well. you can simply export the FeatureModule from the CoreModule . And since you've already imported the CoreModule in the AppModule you'll have access to all the exported members of the CoreModule and FeatureModule is one of them.

Here's what Angular's Docs say, to help you understand better:

The set of components, directives, and pipes declared in this NgModule that can be used in the template of any component that is part of an NgModule that imports this NgModule. Exported declarations are the module's public API.

A declarable belongs to one and only one NgModule. A module can list another module among its exports, in which case all of that module's public declaration are exported.

Declarations are private by default. If this ModuleA does not export UserComponent, then only the components within this ModuleA can use UserComponent.

ModuleA can import ModuleB and also export it, making exports from ModuleB available to an NgModule that imports ModuleA.

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