Tuesday, 9 April 2019

Angular - scope of services

@angular/cli: 7.3.7

Services are a powerful tool in Angular when it comes to storing data or application state. This article is a quick refresher on the various scopes supported by an Angular service.

In order to allow a service to be used, it needs to be declared in the provider section of a module or component.

However, depending on the place where the service is registered, its scope varies accordingly. Let us see how:

a) Service registered in AppModule.ts: This is the root module of your application, and a service registered here holds its state throughout the application. Any value changed here is accessible from any component in the AppModule. This is primarily done for storing data on a global scale, e.g., login state or  client token, etc.

b) Service registered in your custom module: The state of the service holds so long the application navigates to any of the router links registered in this module's router.

c) Service registered in a component: As seems obvious, the scope of this service instance is till the specific component is in use. The state is lost when we navigate away from this component. We register a service on a component only when we need specific functionalities for a component, which does not depend on application state.

We will see a quick demo to illustrate this behaviour.

This sample application has two components (one and two). Two services (LocalService and GlobalService) are in use. The LocalService is defined at the OneComponent, and the GlobalService is defined at AppModule.

GlobalService in AppModule, LocalService in OneComponent

Each service has a variable, which we would update from the OneComponent.

Variables in both services updated

Now the variables in both the services are updated. No problem with that. Let's navigate to the "two" component and come back to "one".

LocalService reset, GlobalService retained
We see that the variable in LocalService has been reset to its original value, while the variable in GlobalService has retained its value.

This is expected since the GlobalService was defined in AppModule and it holds its state throughout the life-cycle of the application. The LocalService was defined in OneComponent, and its state was lost the moment we navigated to a different component.

You can download the source from GitHub.


No comments:

Post a comment