Angular Service (GET) — #2

Rafael Neves
angularbr
Published in
3 min readMar 16, 2022

Hey folks,

Let`s talk in this chapter about Angular Services.

Introduction

Services in Angular are a medium to of communication between components.
The services are a great way to share data that doesn't know each other.
In this article we will build an app that will get a lot a of Digimon from an API-Rest.

Starting the app on your terminal:

ng new servicePoc

Once your repo was created, let's create a service class:

Something like this will be presented:

service.service.ts

Adding httpClient, injectin on the constructor as private httt: HttpClient.

HttpClient is a npm Angular package for making API calls over the backend server, to communicate frontend and backend and present a dynamic web app.

Injecting a Service

service.service.

Right now our project will have that face config.

Do not forget to import the HttpClientModule on app.module:

app.module

Note that we created a method inside the service ( getDigimonList). To call achieve the data from our API, check the JSON on link bellow:

https://digimon-api.vercel.app/api/digimon

In the link, note on service that was separated to link to the route this is because if we need to get another routes, will be easy to provide the maintenance.
How many routes we need, we can add like above ( personally I find it easier).

With this did, now we will inject this service on component and present the html.
We can inject a service in a component, as following below:

app.component.ts

In the constructor , we can inject Service and we have subscribe the getAll list method to get the data and use it. On this particular example we will obtain the lista data from the api. Do not forget of call the method on ngOnInit() to start the app and has the method on execution.

Follow below the Html where we will present the data:

app.component.html → we use bootstrap 5 on this project

The final is result will be something like that:

Conclusion

— The structure of angular app, once that we use to not repeat the code more the one time, the service centralize our business logic.
— Can be easily injected by dependency injection.
— They are very useful to use in more the one component.

To sum up, they must have contain logic. They need to be completely apart from view schemes.

So, this is it guys.
To checkout the code, follow the link of repo on github:
https://github.com/RafaelNevesdeOliveira/ServicePoc

--

--

Rafael Neves
angularbr

Desenvolvedor de sistemas, apaixonado por tecnologia e novos aprendizados. Compartilhando insights no Medium.