Angular 4 HTTP Get Example

Angular HTTP Service

In this tutorial i will be showing you how to create a simple text input which will accept a city name, then it will request the weather of that city from OpenWeatherMap free API service.

Angular 4 HTTP Get Example

Click here if you prefer the Angular HTTP get example video tutorial.

Perquisites:

 

 

First i will create a input box and a button which will trigger the HTTP request, for the button it will be calling a searchCity function which we will create later.

app.component.html

[(ngModel)]=cityName --  ngModel to bind cityName variable I am using the below

<input type="text" [(ngModel)]=cityName>

Next step to create a button to trigger the http request

<button (click)=searchCity()>Search</button>

Next will import the http service in the component. And also import response which will be used to register and assign the response into a variable.

app.component.ts

import { Http , Response} from '@angular/http' ;

Inside the class we need to do the following:

Create http constructor

constructor(private http: Http) { }

Then i will create the function which is triggered by the button we created. In this function i will be calling the api while adding the input text box value as a parameter called cityName

searchCity() {
this.http.get('http://api.openweathermap.org/data/2.5/weather?APPID=0ba5e82df49a15a79cec569618c56215&q=' + this.cityName )
.subscribe (
(res: Response) => {
const weatherCity = res.json() ;
console.log(weatherCity)
})}

 

After running the project using ng serve, you can test it by right click and choose console to find something similar to below image.

Angular 4 HTTP Service

 

 

 


Subscribe to
for video tutorials updates