Your Web News in One Place

Help Webnuz

Referal links:

Sign up for GreenGeeks web hosting
April 5, 2022 01:35 am

Beginner's Guide to Angular: Services


Hello there, I hope you've followed along with our tutorials on Angular components, and routing. In this post, we'll go on to another interesting concept in Angular: services. 



If Angular components are the presentation layer of our application, what will be responsible for actually fetching real data and executing business logic? This is exactly where Angular services come in. The role of an Angular service is to fetch, organise and eventually share data, models and business logic across components. 


Before we dive into the technical details of an Angular Service, let's understand more about it's features. This will help you understand, which part of the code needs to be placed inside a component, and which part needs to be inside an Angular Service.


Here are some important facts about services:


A service is defined with the @Injectable decorator. This tells Angular that the service can be injected into components or other services. We'll talk more about injecting services later.


Services are a place for holding all your business logic and sharing it across components. This makes your application more scalable and maintainable. Often services are the right spot for interacting with the back-end as well. For example, if you need to make AJAX calls, methods for completing the call can be made inside a service.


Services are singleton classes. You will only have a single instance of a specific service running in your Angular application.


What is a Service?


Services in Angular are objects that are instantiated only once in the application's lifetime. Data received and maintained by a Service can be used across the application. This means, components can fetch data from a service at any point in time. Dependency injection is used to introduce services inside components. 


Let's try to understand how to create a service and use it in an Angular component. You can find the complete source to this project in our GitHub repo.



Once you have the source code, navigate to the project directory and install the required dependencies using npm install. After the dependencies have been installed, start the application by typing the following command:



You should have the application running on https://localhost:4200/.


The overall folder structure of our project will be as follows.




1. Building the Skeleton of the Service


There are two ways of creating a service in Angular.



  1. Manually create folders and files inside the project.

  2. Use the ng g service <path/service_name> command to create a service automatically. When you use this approach, you will automatically get a .service.ts, and a .service.spec.ts file in the chosen directory.




2. Creating the Service


Now that the .service.ts file has been created in your project structure, it is time to fill the contents of the service. To do this, you must decide on what the service needs to do. Remember, you can have multiple services, each to perform a specific business operation. In our case, we are going to use the employee.service.ts to return a static list of roles to any component that uses it.


Enter the following code in employee.service.ts.



This service just returns a static list of roles to the application. Let's decode the service, line by line.



  1. We import Injectable from the @angular/core library. This is crucial, because our services will be used or, injected into components. The @Injectable directive allows us to identify services. 

  2. Next we apply the @Injectable decorator. The providedIn property of @Injectable specifies where the injectors will be available. Most of the time, root is assigned as its value. This means the service can be injected at application level. The other options are any, platform, null or Type<any>. 

  3. We create a class component, with the name EmployeeService. This class has a method getRole, which returns a static array of objects.



3. Create a Component


As mentioned before, services in Angular are used to hold the business logic of the application. In order to show data to the viewer, we need a presentation layer. That's where the traditional class-based Angular components come in, created using the decorator @Component.


You can learn more about Angular components in my previous post in this series. It will help you understand Angular components and create your own component. Create the file employee.component.ts and add the following code to it:



Let's break it down



  1. Import the @Component decorator and invoke it. We specify 'employee' as the selector, and we provide a template URL pointing to the HTML describing the view of the component. 

  2. Declare the component class and specify that it implements OnInit. As a result, we can define an ngOnInit event handler which will be called when the component gets created.

  3. In order to use our service, it has to be declared inside the constructor. In our case, you will see private employeeService: EmployeeService in the constructor. With this step, we will making the service accessible across the component. 

  4. Since our goal is to load the roles when the employee component is created, we fetching the data inside ngOnInit. 


Can this get any more simpler? Since the service is a singleton class, it can be reused across multiple components without any performance penalty.  



4. Creating a View


Now that we have data in our component, let's build a simple employee.component.html file to iterate through the roles, and display them. Below we make use of *ngFor to iterate through roles, and display only the type to the user.




5. Running the Project


We only have one more step before the project gets up and running. We need to make sure that the employee.component.ts file is included in our list of declarations, inside the @NgModule directive.


As seen below, EmployeeComponent is added into the app.module.ts file. 



Interestingly, we have not added the service in our list of providers. Yet, we are able to use the service successfully. Why? Because, we have specified that the service is to be provided at the application's root level (ie. with the providedIn: 'root' parameter). However, keep reading to understand more about a scenario where we do need to mention a service in the providers array of @NgModule.


Also, we need to add the employee element into the app.component.html file.



If we run our app so far, it will look like this:


screenshot of the completed appscreenshot of the completed appscreenshot of the completed app


6. Fetching Data Dynamically from a Service


Now, we are going to fetch data specific to our employee.component.ts. 


Let's create a new service to fetch data from an API.



Now, let's understand our code line by line.



  1. Since we are ought to fetch data through an AJAX call, it is important to import HttpClient. If you are new to HttpClient, and you can [learn more about it in another post in this series].

  2. In our EmployeeDetailsService, we are not specifying the provideIn parameter. This means we need to do an additional step to tell the entire application know about our injectable service. You'll learn about this in the next step.


  3. HttpClient is itself an injectable service. Declare it in the constructor so it will be injected into the component. In the fetchEmployeeDetails method we'll use the HttpClient.get method for fetching data from a URL.



7. Registering the Service in app.module


Unlike our first service, it is crucial for us to register the EmployeeDetailsService in app.module.ts. Since we have not declared the injectable at root level. Here's the updated app.module.ts file:



If you're following closely you might have noticed two important changes: 



  1. In our app.module.ts file, we need to include EmployeDetailsService in the list of Providers. 

  2. We need to import HttpClientModule from @angular/common/http. HttpClientModule has to be included in our list of imports.


That's it, we are now ready to make use of EmployeeDetailsService in our component.



8. Fetching Dynamic Data


In order to accommodate the new service, we are going to do few changes in our component.


Add a Button to Load the Data


First we'll add a button to our view. When we click this button, the data will be loaded via an AJAX call. Here's the updated employee.component.html file:



Subscribe to the Getter Function


Next, subscribe to the getter function, in the EmployeDetailsService. To achieve this, we will be adding EmployeDetailsService to our constructor in employee.component.ts:



With this change, and on clicking the LoadEmployeeDetails button, we would see the following view.


screenshot of the completed appscreenshot of the completed appscreenshot of the completed app

Conclusion


There you go, we have gradually built an Angular Services that can deal with static and dynamic data. Now, you should be able to build your very own Angular services, and use them to fetch data through AJAX calls. And you can even implement your business logic in a more reusable fashion.



Original Link: https://code.tutsplus.com/tutorials/beginners-guide-to-angular-4-services--cms-29675

Share this article:    Share on Facebook
View Full Article

TutsPlus - Code

Tuts+ is a site aimed at web developers and designers offering tutorials and articles on technologies, skills and techniques to improve how you design and build websites.

More About this Source Visit TutsPlus - Code