In this tutorial, we will take a look at services in Angular 5. Services are very useful because they make your code reusable. You can use the code everywhere on the page and your code can be accessible to the entire application. We can create methods, properties, and data connections within services, and then we can access them from others components.
Previous Tutorials of Angular 5 series.
- How to install angular 5 using VS Code.
- Components in Angular 5.
- What is Module in Angular
- Data Binding in Angular 5.
- Routing in Angular 5
How to implement Services in Angular 5?
Let’s see how to implement services in Angular 5.
We will use Angular CLI Command to create a service in our project. Now, go to command terminal => and write this below command in your vs code terminal.
ng g service angularservice
Then you will see the output in your terminal as you see in below.
Now, the above command will create the two files in your folder structure which are “angularservice.service.spec.ts” and “angularservice.service.ts”.
Now, before going to next we need to add the service reference to our project’s main parent app.module.ts class as you see below.
Line # 5: As you see in this line we are importing the service with the class name.
Line # 27: Now in this line we are using the same name of class which we are importing in Line # 5.
How to create a function in service?
Now, in this step, we will create a function in Angularservice which we can use in other components. Let’s open the file “angularservice.service.ts” and you will see some code within this file as you see below.
Line # 1: This class is importing from @angular/core.
Line # 3: It contains the @Injectable method.
Line # 6: This is the class where we will create a function in this class.
Let’s add a new function in the service class.
Line # 9: In this line, we are creating a function with the name “currentDate” which will return the today’s date.
How to access service function in the component class?
Let’s open the “app.component.ts” file as you see in the below.
Line # 1: In this line, we are importing Angularservice.
Line # 12: In this line, we are creating a constructor.
Line # 13: Creating a function ngOnInit function which gets called by default.
Line # 14: This line is fetching the service from angularservice service.
How to display service result in HTML page?
Open the app.component.html file and paste the below code in your app.component.html file as you see below code.
- {{ currentDate }}
Line # 5: Displaying the currentDate result from service.
Let’s run your application and you will see the result as you see below screenshot.
So, you can add this service function in any component same as the above.
Leave a Reply