Sharing Components and Services between Modules

Asked

Viewed 175 times

2

In the development of Angular projects, it is common to share components and services between the various modules that the application may have.

When it comes to services, Angular projects tend to follow a standard Singleton, that is, a service instance for the entire scope.

So for example, imagine a service called AuthService (is an authentication service) therefore declaring the service in the providers of app.module, this instance will be available to all application:

  @NgModule({
  declarations: [
    AppComponent
  ],
  imports: [
    AppRoutingModule,
    SharedModule 
  ],
  providers: [
    AuthService
  ],
  bootstrap: [
    AppComponent
  ]
})
export class AppModule { }

If you want to use this instance in some component, just perform dependency injection.

More details can be found at: Singleton services

When sharing components, we have to use metadata exports instead of providers in the module that the components are being declared:

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

However, even if the module SharedModule is imported into the module AppModulo, as can be seen above, it is not available to any application, it is necessary to import the module SharedModule in each module that will use the component NavBarComponent.

I would like to confirm that this understanding is indeed correct, as can be read in this passage:

Import modules when you want to use Directives, Pipes, and Components. Importing a module with services Means that you will have a new instance of that service, which typically is not what you need (typically one wants to reuse an existing service).

Available in: Sharing modules

  • 1

    that’s right you have to import the module with the component in each module that is utulizalo

No answers

Browser other questions tagged

You are not signed in. Login or sign up in order to post.