I have a JSON file stored locally containing various data. My goal is to extract the CityCodes specifically and store them in an array. Then, I plan to send these CityCodes as part of the OpenWeatherMap API request. Finally, I aim to display all the weather records within the HTML file.
CityData.json:
{
"List": [
{
"CityCode": "1248991",
"CityName": "Colombo",
"Temp": "33.0",
"Status": "Clouds"
},
{
"CityCode": "1850147",
"CityName": "Tokyo",
"Temp": "8.6",
"Status": "Clear"
},
{
"CityCode": "2644210",
"CityName": "Liverpool",
"Temp": "16.5",
"Status": "Rain"
}
]
Weather.Service.ts :
import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { map } from 'rxjs/operators';
@Injectable({
providedIn: 'root'
})
export class WeatherService {
apiKey = '9402da6bd74c395f71604c624cc2b231';
url;
constructor(private http:HttpClient) {
this.url='http://api.openweathermap.org/data/2.5/group?id='; //API GET URL
}
getWeather(cityCode){
return this.http.get(this.url+cityCode+'&units=metric&appid='+this.apiKey);
}
}
home.component.ts :
Currently passing the area code manually but looking to automate this with the CityCodes fetched from the JSON file.
import { Component, OnInit } from '@angular/core';
import { WeatherService } from "../shared/weather.service";
// import { weather} from "../shared/weather.model";
@Component({
selector: 'app-home',
templateUrl: './home.component.html',
styleUrls: ['./home.component.css']
})
export class HomeComponent implements OnInit {
location={
code: '1248991' //Passing Area Code Manually
};
public weather: any;
constructor(private weatherService:WeatherService) {
}
ngOnInit() {
this.weatherService.getWeather(this.location.code).subscribe((Response:any)=>{
console.log(Response);
this.weather = Response.list;
})
}
}
home.component.html :
<table class="table table-hover">
<thead>
<th>City</th>
<th>City Code</th>
<th>Temperature</th>
<th>Description</th>
</thead>
<tbody>
<tr *ngFor="let weather of weather">
<td>{{weather.name}}</td>
<td>{{weather.id}}</td>
<td>{{weather.main.temp}}</td>
<td>{{weather.weather[0].description}}</td>
</tr>
</tbody>
</table>