In this Video, I am going to discuss Angular Services with examples. Please watch our previous Video where we discussed how angular routing works in detail. As part of this Video we are going to discuss the following pointers.
- What are Angular Services?
- Why do we need a services in Angular?
- How to create a service in Angular?
- How to use register and use angular services?
- Difference between constructor and ngOnInit to call angular services.
What are Angular Services?
The Angular Services are the piece of code or logic that are used to perform some specific task. A service can contain a value or function or combination of both. The Services in angular are injected into the application using the dependency injection mechanism.
Why do we need a service in Angular?
Whenever you need to reuse the same data and logic across multiple components of your application, then you need to go for angular service. That means whenever you see the same logic or data-access code duplicated across multiple components, then you need to think about refactoring the same logic or data access code into a service.
There is a principle in software development i.e. DRY (Dont Repeat Yourself) and using services in angular safely follow this principle. The logic or data is implemented in a services and the service can be used across multiple components of your angular application. So, services is a mechanism used to share the functionality between the components.
Without Angular Services, you would have to repeat the same logic or code in multiple components wherever you want this code or logic. Now think about the overhead in terms of time and effort required to develop, debug, test and maintain the duplicated code across multiple places instead of having that duplicated code at one central place like a service and reusing that service where required.
Understanding Angular Service with an example:
Let us Angular Service step by step with an example. First we will understand how to create angular service and then we will discuss how to use angular service within a component.
Step1: Creating Angular Service
The angular service is composed of three things. You need to create an export class and you need to decorate that class with @Injectable decorator and you need to import the Injectable decorator from the angular core library. The syntax to create angular service is given below.
Let say you want to create an angular service for fetching the student details and this student details is going to be used by many components. So, open terminal and type ng generate service Student and press enter as shown below.
Once you press the enter button it will create two files within the app folder as shown below.
Modifying student.service.ts file:
Open student.service.ts file and then copy and paste the following code in it. At the moment we have hard-coded the student data, later in this Video series we will discuss how to get this data from restful APIs. Here, you need to focus on two things. The @Injectable decorator and the getStudents method which returns the student data. As with all other angular decorators, we preceded the name with an @ symbol, and we do not add a semicolon (;) at the end.
Note: The @Injectable() decorator in angular is used to inject other dependencies into the service. At the moment our service does not have any other dependencies, so, yo can remove the @Injectable() decorator and the service should works. However, the Angular Team recommends to always use @Injectable() decorator to ensures consistency.
Step2: Using the Service in Angular
Once you created the service, the next and the important step is to inject and use the service within the components. It is a three step process. Import the service, register the service and use the service. The syntax is given below.
Here, first we import the service. Then we need to register the Service in the component by declaring it in the providers array. Then we need to Inject StudentService using the constructor. The private variable _studentService which points to StudentService singleton instance is then available throughout the class.
Here, we want to use the Student Service within our AppComponent class.
Modifying app.component.ts file:
Open app.component.ts file and then copy and paste the following code in it.
As you can see in the above code, we declare one variable called students and then initialize this variable using the student service.
Modifying app.component.html file:
Now, open app.component.html file and then copy and paste the following code in it.
With the above changes in place, now browse the application and you should see the student data as expected in the browser as shown in the below image.
Using ngOnInit() life cycle hook to call the getStudents() service method:
Let us see how to use ngOnInit to call the service method and then we will see the difference between calling the service method from a constructor and from ngOnInit life cycle hook. So, modify the app.component.ts file as shown below to use ngOnInit life cycle hook to call the getStudents method of Student Service.
With the above changes, you will also get the same output.
Difference between constructor and ngOnInit
Whenever you create an instance of a class, the class constructor is automatically called. Like other programming languages, the class constructor in angular is also used to initialize the members of the class and its sub classes.
The ngOnInit is a life cycle hook method provided by Angular which is called after the constructor and is generally used to perform tasks related to Angular bindings. For example, ngOnInit is the right place to call a service method to fetch data from a remote server. We can also do the same using a class constructor, but the general rule of thumb is, tasks that are time consuming should use ngOnInit instead of the constructor. As fetching data from a remote server is time consuming, the better place for calling the service method is ngOnInit.
In our example, the dependency injection is done using the class constructor and the actual service method call is issued from ngOnInit life cycle hook as shown below.
In the next Video, I am going to discuss Dependency Injection in Angular. Here, in this Video, I try to explain the Angular Services with an example and I hope now you understand what are angular services and why do we need them in angular application.