Http Hobo

Another blog with web-development tips’n’tricks. | About me

Angular 2+ service doesn’t feel being shared across components?

Probably the reason is that you’ve declared it as a component provider, not app provider. Shared service has to be declared in app.component.ts in “providers” section:

@NgModule({
  declarations: [
    // Some declarations
  ],
  imports: [
    // Some imports
    RouterModule.forRoot(
        appRoutes,
        { enableTracing: true }
    )
  ],
  providers: [
      YourService,
  ],
  bootstrap: [AppComponent]
})
export class AppModule { }

If you declare it in component declaration like this:

@Component({
    selector: 'my-component',
    templateUrl: './templates/my-component.component.html',
    providers: [MyService],
})

then a fresh instance of a service will be created, instead of using a app-wide one.

If you need a service instance shared across components, declare it app-wide. If you need a distinct service instance for a component, declare it as a component’s provider.

2017   angular
Popular