Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular - Should HttpClientModule be in the Exports array in the CoreModule?

Well, I'm structuring my project following the infrastructure of:

  • Feature module.
  • Core module.
  • Shared module.

But there's something that I still don't have clear enough.

As far as I know, the HttpClientModule should be in the CoreModule because well,... it provides the HttpClient service to make HTTP requests to a server.

Now, the imports array allows an Angular module to use functionalities provided in other modules, and the exports array allows an Angular module to expose some of its functionalities.

I have this in my CoreModule:

@NgModule({
    imports: [
        BrowserAnimationsModule,
        HttpClientModule,
        RouterModule.forRoot(routes, {
            enableTracing: true
        })
    ],
    exports: [
        RouterModule
    ]
})
export class CoreModule {
}

Now, since my CoreModule is imported in my AppModule, shouldn't the HttpClientModule and BrowserAnimationsModule be exported as well? Just as the RouterModule.

I'm seeing the CoreModule and SharedModule like some sort of bridge.

The SharedModule makes more sense to me:

@NgModule({
    imports: [
        MatButtonModule
    ],
    exports: [
        MatButtonModule
    ]
})
export class SharedModule {
}

The SharedModule imports the MatButtonModule and then export it so that other modules can make use of it.

Shouldn't the CoreModule be the same way? Because the App runs fine; however, I'm in dev-mode.

Hope I was clear enough and someone can help me to brush out this doubt.

like image 581
RottenCheese Avatar asked May 09 '18 20:05

RottenCheese


Video Answer


1 Answers

No, the exports array of an NgModule shouldn't include modules without components, directives, or pipes (like HttpClientModule).

The purpose of exporting something from an NgModule is to give other modules (or things within those other modules) access to this module's components, directives, and pipes—and also sometimes to give those other modules access to (i.e. re-export) components, directives, and pipes from some other module as a convenience.

Your CoreModule lists RouterModule as an export so that anything importing your CoreModule can use the routerLink attribute directive (among other things). That is, RouterModule exports components, directives, and/or pipes.

As the HttpClientModule doesn't declare any components, directives, or pipes, there is no value in listing it as an NgModule export.

These Angular guide NgModule FAQs may also be useful:

  • What should I export?
  • What should I not export?
like image 126
Alex Peters Avatar answered Sep 27 '22 21:09

Alex Peters