Table of Contents
Creating a weather application is an excellent way to learn how to integrate third-party APIs with Angular. In this tutorial, we will build a simple weather app using Angular and the OpenWeatherMap API. This project will help you understand how to fetch data from an API and display it dynamically in your Angular app.
Prerequisites
- Basic knowledge of Angular framework
- Node.js and npm installed on your computer
- An API key from OpenWeatherMap (sign up at openweathermap.org)
Setting Up the Angular Project
Start by creating a new Angular project using the Angular CLI:
ng new weather-app
Navigate into the project directory:
cd weather-app
Obtaining the OpenWeatherMap API Key
Register on OpenWeatherMap to get your free API key. Once you have it, store it securely, as you’ll need it to make API requests.
Creating the Weather Service
Generate a new service to handle API calls:
ng generate service services/weather
Open the weather.service.ts file and add the following code:
import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { Observable } from 'rxjs';
@Injectable({
providedIn: 'root'
})
export class WeatherService {
private apiKey = 'YOUR_API_KEY'; // Replace with your OpenWeatherMap API key
private apiUrl = 'https://api.openweathermap.org/data/2.5/weather';
constructor(private http: HttpClient) { }
getWeather(city: string): Observable
return this.http.get(`${this.apiUrl}?q=${city}&appid=${this.apiKey}&units=metric`);
}
}
Creating the Weather Component
Generate a new component:
ng generate component components/weather
Open weather.component.ts and update as follows:
import { Component } from '@angular/core';
import { WeatherService } from '../../services/weather.service';
@Component({
selector: 'app-weather',
templateUrl: './weather.component.html',
styleUrls: ['./weather.component.css']
})
export class WeatherComponent {
city: string = '';
weatherData: any = null;
constructor(private weatherService: WeatherService) { }
getWeather() {
this.weatherService.getWeather(this.city).subscribe(data => {
this.weatherData = data;
});
}
}
Designing the Weather Template
Open weather.component.html and add the following code:
Temperature: {{ weatherData.main.temp }} °C Weather: {{ weatherData.weather[0].description }} Humidity: {{ weatherData.main.humidity }}%
Weather in {{ weatherData.name }}
Final Steps
Make sure to import the HttpClientModule in your app.module.ts:
import { HttpClientModule } from '@angular/common/http';
@NgModule({
imports: [
HttpClientModule,
// other imports
],
// other configurations
})
Finally, include the <app-weather> selector in your app.component.html to display the weather widget:
<app-weather></app-weather>
Now, run your app with ng serve and test it by entering different city names to see the weather data fetched from OpenWeatherMap.