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

Implementing an HTTP GET operation

Now, we can implement the GET call in the Weather service:

  1. Add a new function to the WeatherService class named getCurrentWeather
  2. Import the environment object
  3. Implement the httpClient.get function
  1. Return the results of the HTTP call:
src/app/weather/weather.service.ts
import { environment } from '../../environments/environment'
...
export class WeatherService {
constructor(private httpClient: HttpClient) { }

getCurrentWeather(city: string, country: string) {
return this.httpClient.get<ICurrentWeatherData>(
`${environment.baseUrl}api.openweathermap.org/data/2.5/weather?` +
`q=${city},${country}&appid=${environment.appId}`
)
}
}

Note the use of ES2015's String Interpolation feature. Instead of building your string by appending variables to one another like environment.baseUrl + 'api.openweathermap.org/data/2.5/weather?q=' + city + ',' + country + '&appid=' + environment.appId, you can use the backtick syntax to wrap `your string`. Inside the backticks, you can have newlines and also directly embed variables into the flow of your string by wrapping them with the ${dollarbracket} syntax. However, when you introduce a newline in your code, it will be interpreted as a literal newline—\n. In order to break up the string in your code, you may add a backslash \, but then the next line of your code can have no indentation. It is easier to just concatenate multiple templates, as shown in the preceding code sample.

Note the use TypeScript Generics with the get function using the caret syntax like <TypeName>. Using generics is development-time quality of life feature. By providing the type information to the function, input and/or return variables types of that function will be displayed as your write your code and validated during development and also at compile time.

主站蜘蛛池模板: 元朗区| 鲁山县| 尚志市| 安仁县| 苍山县| 静海县| 东平县| 开江县| 太谷县| 安多县| 斗六市| 阜南县| 夏津县| 梧州市| 方城县| 永兴县| 铜山县| 边坝县| 武隆县| 从江县| 中宁县| 北宁市| 运城市| 蚌埠市| 濮阳市| 大港区| 论坛| 巨野县| 宜良县| 靖边县| 泸州市| 西盟| 太和县| 师宗县| 瓮安县| 衡水市| 贵州省| 浠水县| 屯昌县| 西和县| 沅陵县|