Generating Services
In this lesson, we'll learn what services are and how to create them.
We'll cover the following
Our form is ready. It’s sending the search query to the App component, where we’ll perform the request for the data. There are two approaches we can take for making a request. The first is to request the data in the component. The second is to request the data in a service.
What are services?
Services are objects with methods and properties for fetching data. They’re responsible for creating, updating, and fetching data. We don’t have to use services. They’re a completely optional feature of Angular.
If we want to, we can request the data from the component. However, chances are we’ll want to make multiple requests to the same data source. This means we’ll have to retype the request in every component in which we’d like to perform a request.
By outsourcing requests to an object, we only need to type the request once. Then, we can import the service into any component and use the service to make the request for us. The goal of a service is to supply data to a component(s). Anytime you need to make an API request, you’ll want to put it in a service.
Generating a service
Services are created with the ng generate service <name>
command. What a surprise, right? We’ll be generating a service to handle requests to the Cocktail DB API.
Let’s run the following command in our project:
ng generate service cocktail
This will create two files: cocktail.service.ts
and cocktail.service.spec.ts
. The spec
file in its name is the testing file for the service. Testing is something we’ll look at in another section.
Our main focus will be on the cocktail.service.ts
file.
Using the service
One thing you may notice during the generation of the service file is that the CLI did not register the service anywhere. This is because services are not bound to any component or module. They can be used anywhere.
If we want to use the service, we’ll need to import it. We’ll be using the service in the App component. We’ll update the app.component.ts
to the following:
Get hands-on with 1400+ tech skills courses.