官术网_书友最值得收藏!

Discover OpenWeatherMap APIs

Since httpClient is strongly typed, we need to create a new interface that conforms to the shape of the API we'll call. To be able to do this, you need to familiarize yourself with the Current Weather Data API.

  1. Read documentation by navigating to http://openweathermap.org/current:

OpenWeatherMap Current Weather Data API Documentation

You will be using the API named By city name, which allows you to get current weather data by providing the city name as a parameter. So, your web request will look like this:

api.openweathermap.org/data/2.5/weather?q={city name},{country code}
  1. On the documentation page, click on the link under Example of API calls, and you will see a sample response like the following:
http://samples.openweathermap.org/data/2.5/weather?q=London,uk&appid=b1b15e88fa797225412429c1c50c122a1
{
"coord": {
"lon": -0.13,
"lat": 51.51
},
"weather": [
{
"id": 300,
"main": "Drizzle",
"description": "light intensity drizzle",
"icon": "09d"
}
],
"base": "stations",
"main": {
"temp": 280.32,
"pressure": 1012,
"humidity": 81,
"temp_min": 279.15,
"temp_max": 281.15
},
"visibility": 10000,
"wind": {
"speed": 4.1,
"deg": 80
},
"clouds": {
"all": 90
},
"dt": 1485789600,
"sys": {
"type": 1,
"id": 5091,
"message": 0.0103,
"country": "GB",
"sunrise": 1485762037,
"sunset": 1485794875
},
"id": 2643743,
"name": "London",
"cod": 200
}

Given the existing ICurrentWeather interface that you have already created, this response contains more information than you need. So you will write a new interface that conforms to the shape of this response, but only specify the pieces of data you will use. This interface will only exist in the WeatherService and we won't export it, since the other parts of the application don't need to know about this type.

  1. Create a new interface named ICurrentWeatherData in weather.service.ts between the import and @Injectable statements
  2. The new interface should like this:
src/app/weather/weather.service.ts
interface ICurrentWeatherData {
weather: [{
description: string,
icon: string
}],
main: {
temp: number
},
sys: {
country: string
},
dt: number,
name: string
}

With the ICurrentWeatherData interface, we are defining new anonymous types by adding children objects to the interface with varying structures. Each of these objects can be inpidually extracted out and defined as their own named interface. Especially, note that weather will be an array of the anonymous type that has the description and icon properties.

主站蜘蛛池模板: 二连浩特市| 彭山县| 启东市| 博野县| 嘉黎县| 榆树市| 霍城县| 开远市| 湾仔区| 巴彦县| 蒙山县| 酒泉市| 沈丘县| 商都县| 会东县| 溧阳市| 土默特左旗| 铁岭市| 阳高县| 筠连县| 崇义县| 驻马店市| 金秀| 苏州市| 江源县| 偏关县| 北宁市| 鄂伦春自治旗| 平昌县| 萨嘎县| 宝兴县| 留坝县| 库伦旗| 淄博市| 彝良县| 长寿区| 犍为县| 平塘县| 辽宁省| 西乌珠穆沁旗| 怀仁县|