Saturday, August 15, 2020

Angular Singleton Services

A Singleton Service is one which has only one instance shared across the entire Angular App, it is a great way to share data across different components even if they don’t have any Hierarchal relationship. Services can be declared Singleton by setting the providedIn property of the @Injectable() to "root", when creating the service.

@Injectable({
  providedIn: 'root',
})
Provider are used for Dependency Injection, they create or deliver a service to the component. When you are providing service in the root module it makes service global and that service is used by all the components.

Module level Singleton
We can also register a singleton service at a Module level by adding the service to the providers[] array of the module declaration.

@NgModule({
  providers: [
  HelloService,
 ],
})

With this approach the service is Singleton for the module, however if there are child modules lazy loaded using Feature modules then the feature modules will create a separate copy of the service. This can be prevented by setting the providedIn property of the @Injectable() to "root", this will make sure that the service is truly singleton across the application even for lazy loaded feature modules.


Search Flipkart Products:
Flipkart.com

No comments: