Creating a shared service in Angular 2

 Dec 05, 2016

Today, I will be taking a closer look at creating a shared service instance that can be used within an Angular 2 application. As development continues on your Angular 2 application, you might at some point reach a stage where you need to start thinking about reducing the amount of duplicate code that we create, share information between components or even create shared functionality such as logging.

With this in mind, your best bet is to create a service in Angular 2 and then share the service across your whole application so that any component can reference and use it when needed. Before we look at shared services you have to understand that Angular 2 has two types of services, one called Dedicated Instances and the other Shared Instances.

When we talk about a Dedicated Instance, this is a service that is injected into a component directly and is then used within the component. These injectors exist in a hierarchy, so when a component doesn’t know about a service it will look at the parent’s component to see if it is injected there and this will keep going up the hierarchy until it reaches the root Injector (specified in the main.ts file). Remember this hierarchy when defining your services because it will make your life either easier or harder.

Although dedicated instances are great, they are called dedicated for a reason. You will normally use these types of services to provide functionality to a specific component or have it create a separate instance for each component as opposed to one instance used by multiple components. On the other hand, when we need to reuse functionality we should look towards using a shared instance. For example, if our application requires logging.

As part of this blog I will showcase the needed code for creating a shared instance that is specified at the root level and can then be used throughout the application. In order to make this happen I have to first create a service that will be acting as the Shared Instance, in my case I will be creating a very basic logging service. Our logging service will have the capabilities to log Errors, information and warnings to the browser console when called upon.

The service we are creating will have the following code:

In this service we have three methods, each accepting the same input argument of type “any[]”, by providing this type of input argument we can pass in an array containing a variety of data to be used by the method. The methods will perform the following actions:

  • If the error method is called: Log the given data as an error entry
  • If the info method is called: Log the given data as an information entry
  • If the warn method is called: Log the given data as an warning entry

Once the Service is created we can then inject the service into the Root Injector to make sure all the components in our application can use the service when called upon. To perform this step we need to open the app.module file and modify it, the modification should look like the following image:

In the image illustrated above, take note of the following lines of code:

  • Line 4: This imports the Logging Service into the Root Module so that we can use it
  • Line 10: We added the provider’s property and included the Logging Service in the array, this will now provide all other components access to the same provider.

Because we have now created a service and injected it into the root, we can go about using it anywhere in our application. Let’s add some logic to our app.component file to support the usage of our Service.

In the code for the app.component we have completed the following:

  • Line 1: import OnInit, this is a lifecycle hook that will allow us to perform logic once the component is initialised
  • Line 2: Even though the service is added as a provider at the root level, we still need to import a reference to the service if we want to use it in code.
  • Lines 3-7: Note there is no Providers property assigned, this is normally assigned for a dedicated Service. Since we are using a Shared Service we don’t have to specify it
  • Line 8-9: Firstly we implement the OnInit and then we specify a constructor so we can get a reference to the service of interest.
  • Line 11 – 12: This method is fired once the component is initialised, and we will log it to the console by calling the LogTest method and passing in two parameters
    • First parameter is the type of log we want to record
    • Second parameter is the message
  • Lines 14 – 15: This is the method that calls upon the service, we call the LoggingService with the following arguments
    • [type]: this is deciding which method to fire in the LoggingService itself.
    • Message: this is the message to log.

As for the Component’s view, we have the following HTML markup which can test the logging service on demand.

In the code above we created a simple list of link that when clicked on will fire of the LogTest method on the component and in turn fire of the log methods specified in the Service. Here is the description of the coding lines, all of them have a click property bound to the LogTest Method:

  • Line 3: Contains an anchor tag, when the user clicks on this link we send “warn” as our type and a message alongside it.
  • Line 4: Contains an anchor tag, when the user clicks on this link we send in “info” as our type and a message alongside it.
  • Line 5: Contains an anchor tag, when the user clicks on this link we send in “error” as our type and a message alongside it.

When the application runs, we can see the following:

When AppComponent has been initialised we get an Info message logged to the console. If we now click on the links we provided we see the following results:

Take note that there are now three more events logged, one warning, one additional info event and finally an error event. With this configured you can now create more components and still use the same service instance to perform the logging for you. By reproducing the steps for the appcomponent in another component you will be able to reference the same instance of the server.

This concludes my Blog on how to create a basic Share Service that can be reused multiple times wherever it is needed, by following this tutorial you will be able to apply it to your applications as well.

For more information, take a look at New Horizons’ Angular 2 Programming course and Developing Responsive Websites Using Jquery, Angular 2 And Bootstrap.


How do your Excel skills stack up?   

Test Now  

About the Author:

Auret Swanepoel  

As a recent addition to the New Horizons team, Auret is a highly skilled and qualified IT Technical trainer. He has been a Microsoft Certified Trainer (MCT) since 2008 and has since then, also become a Microsoft Certified Professional (MCP), a Microsoft Certified Technology Specialist (MCTS) and a Microsoft Certified Information Technology Professional (MCITP). With his international experience as a trainer in South Africa, Auret is able to adapt his teaching style to different audiences in the classroom and ensure that students are learning in a positive and collaborative environment.

Read full bio
top
Back to top