Angular – shared service between components doesn’t work

If you are providing your DataService inside the providers array of your @Component annotation,

@Component({
    ...
    providers: [DataService],
})...

this service will be a singleton (it will create a new instance) for this component (and it’s children if they have not provided this service under their annotation also).

If you want to use this service among multiple components and share the same instance of the service; you need to provide this service in a component/module which is the parent of these components in the DI tree. If this is a global service I suggest providing it only in your AppModule (or in a shared module).

@NgModule({
    providers:[DataService]
})

Source: https://angular.io/guide/dependency-injection#injector-hierarchy-and-service-instances

Angular 9 Update

Global level services are now defined as

@Injectable({
  providedIn: 'root',
})
export class DataService {

This should be the recommended approach since it will tree-shake itself if it’s unused.

Source: https://angular.io/guide/providers#providedin-and-ngmodules

Leave a Comment