Service Injection in Angular 4

In this section, we will learn more about service injection. Before doing so, let’s create a new service. In the last section, we have understood different stages of ng-hooks. Now, if you have read that post closely, you would have observed one pattern that, I logged messages more often just to prove the point. This is quite repetitive. Therefore, these are the places where services fits in nicely. Main role of any service is to simplify the things. Here, you can think of one dedicated component doing the job. Hence, without wasting time, let’s get started.

Below, I have created a sample logging service under app folder.

With the above change in place, now my logging mechanism has become centralized. Therefore, where-ever, I need to log something, I can make use of my service like shown below. Let’s say, I need to utilize this service in movies.ts file for logging. Then, in that case, first we need to import the same and then in order to use it, we need to inject it via constructor. Below, is the finished snippet movies component.

Similarly, I have modified for reviews component as well. Below, is the finished snippet for the same.

With the above change in place, when I refresh the page and see the logs, everything will be working as excepted, like how it was working previously. But, this time via service.

With this I would like to wrap this first part. In the next part, we will continue this discussion, and understand the gist of service injection. Till then, stay tuned and happy Coding.

Download Code:-

Rahul Sahay,
Happy Coding

218 total views, 1 views today