Using Angular Services and HttpClient to retrieve data
Now you need to connect your CurrentWeather
component to the OpenWeatherMap
APIs. In the upcoming sections, we will go over the following steps to accomplish this goal:
- Create a new Angular Service
- Import
HttpClientModule
and inject it into the service - Discover the
OpenWeatherMap
API
- Create a new interface that conforms to the shape of the API
- Write a
get
request - Inject the new service into the
CurrentWeather
component - Call the service from the
init
function of theCurrentWeather
component - Finally, map the API data to the local
ICurrentWeather
type using RxJS functions so that it can be consumed by your component
Creating a new Angular Service
Any code that touches outside of the boundaries of a component should exist in a service; this includes inter-component communication, unless there's a parent-child relationship, and API calls of any kind and any code that cache or retrieve data from a cookie or the browser's localStorage. This is a critical...