Skip to main content

ASP.NET Core & Angular 2 - Chapter 3 Display the weather

Display the weather

We’ll take a look at how to create a .NET Core Web API controller, retrieve data from it and pass that up to the Angular front end (where it will be rendered as a page on your site).

Add Controller Method

We’ll initially just add a simple method to the WeatherController to make use of the OpenWeather API to get forecast by City.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 26 27 28 29 30 31 32
[HttpGet("[action]/{city}")] public async Task WeatherForecast(string city) { using (var client = new HttpClient()) { try { client.BaseAddress = new Uri("http://api.openweathermap.org"); var response = await client.GetAsync($"/data/2.5/weather?q={city}&appid=[Insert API Key Here ]&units=metric"); response.EnsureSuccessStatusCode(); var result = await response.Content.ReadAsStringAsync(); var openWeather = JsonConvert.DeserializeObject(result);
var forecast = new { Temp = openWeather.Main.Temp, Summary = string.Join(",", openWeather.Weather.Select(x => x.Main)), City = openWeather.Name }; return Ok(forecast); } catch (HttpRequestException httpRequestException) { return BadRequest($"Error getting weather from OpenWeather: {httpRequestException.Message}"); } }
}

I created some Custom Classes to be used to capture the results

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
 public class Description {     public string Main { get; set; } public string Condition { get; set; } } public class Main { public string Temp { get; set; } } public class WeatherResponse { public string Name { get; set; } public IEnumerable Weather { get; set; } public Main Main { get; set; } }

Angular 2 Components

We’ll create a sime very simple Angular 2 Components in order to illustrate how they will all work together to retrieve data, and how they can be further developed to provide more abstraction.

We’ll create a Angular Service to interact with out .net API.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 26 27 28 29 30 31 32
 // Interface Declaration import { Observable } from 'rxjs/Observable'; import { Response } from '@angular/http'; export interface IWeatherService { getWeatherReport(city : string): Observable; } /////////////////////////////////////////////////////////// // Class Declaration import { Injectable } from '@angular/core'; import { Http, Response } from '@angular/http'; import {Observable } from 'rxjs/Observable'; import {IWeatherService } from './weatherservice.interface'; @Injectable() export class WeatherService implements IWeatherService{ constructor(public http : Http){ } getWeatherReport(city : string): Observable{ var url :string = '/api/Weather/WeatherForecast/' + city; return this.http.get(url); } }


We’ll create a very simple class that will interact with the service to get the desired forecast and make it available to the UI to present.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 26 27 28 29 30 31 32
import { Component, OnInit } from '@angular/core'; import { Http } from '@angular/http'; import 'rxjs/add/operator/toPromise'; import { WeatherService } from '../../../services/weather.service'; import { Forecast } from '../../models/forecast.model'; @Component({ selector: 'weather', templateUrl: './weather.component.html' }) export class WeatherComponent implements OnInit {
public forecasts: Forecast; constructor(private service : WeatherService) { } ngOnInit(): void{ // In future we will add a method here to determine users default city // for now we will just set it to hometown this.getWeatherReport('Swindon'); } getWeatherReport(city : string){ this.service.getWeatherReport(city).subscribe(result => { this.forecasts = result.json() as Forecast; }); } }
We’ll create a very simple UI presentation class to present the data

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24
 <h1>Weather forecast</h1> <p>This component demonstrates fetching data from the server.</p> <p *ngIf="!forecasts"><em>Loading...</em></p> <table class='table' *ngIf="forecasts"> <thead> <tr> <th>City</th> <th>Temp. (C)</th> <th>Summary</th> </tr> </thead> <tbody> <tr> <td>{{ forecasts.city }}</td> <td>{{ forecasts.temp }}</td> <td>{{ forecasts.summary }}</td> </tr> </tbody> </table>

Comments