Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

249
Visualizações
When to inject a SERVICE to Angular 2 Module level and App Component Level

I've been watching Angular 2 Getting Started in PluralSight and I saw some Services created are injected in the App Component and Module Component.

Here's example:

When creating a RouterGuard in Angular 2, the created Service for RouterGuard is injected in the Module level but some custom service are injected only to App Component level. My question is, when should I inject a service to Module level and when to inject only to App component level.

Thanks!

about 4 years ago · Santiago Trujillo
1 Respostas
Responde à pergunta

0

Indeed you can provide services at the Module level and at the Component level. You can provide a service at the Module level, by listing it in the providers array of the NgModule like this:

@NgModule({
    declarations: [
        ...
    ],
    imports: [
        ...
    ],
    providers: [MyService],
    bootstrap: [AppComponent]
})

When you do this, you are providing the same instance across the whole Module and all children.

But, at times, you may want to provide separate instances of services to components. In that case, you can provide a service at the Component level by listing it in the providers array in the component decorator like this:

@Component({
    templateUrl: './app.component.html',
    providers: [MyService]
})

This provides a new instance of the service just for this component.

One example of when you want to provide a service at the Module level is when you will use a service to hold data shared by several components. This could be using variables or observables that are stored in the service, but used by several components. Another time you would want to provide a service at the Module level is if your service is stateless(only returns observables from Http calls). In these scenarios, having a shared instance makes sense.

Other times, you may want to provide a service that also holds data, but you want each component to have it's own instance. In this scenario, it makes sense to provide the service at the Component level.

Hope that helps.

about 4 years ago · Santiago Trujillo Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda